如何使Prime Generator代码更高效

时间:2015-03-14 07:17:40

标签: scala

作为Scala的初学者,我在SPOJ中遇到了一个问题:

Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

输入

输入以单行中的测试用例的数量t开始(t <= 10)。在下一个t行的每一行中,有两个数字m和n(1 <= m <= n <= 1000000000,n-m <= 100000)由空格分隔。

输出

对于每个测试用例,打印所有质数p,使得m <= p <= n,每行一个数,由空行分隔的测试用例。

实施例

输入:
2
1 10
3 5

输出:
2
3
5
7个

3
5
` 警告:输入/输出数据较大,请注意某些语言(如果算法设计得很好,大多数应该没问题)

运行环境和要求:

添加者:Adam Dzedzej
日期:2004-05-01
时间限制:6s
来源限制:50000B
内存限制:1536MB
集群:立方体(Intel Pentium G860 3GHz)
语言:除了以下所有:NODEJS PERL 6 SCM鸡

我的代码在这里:

import math.sqrt

object Pro_2 {
  def main(args: Array[String]) {

    // judge whether a Long is a prime or not
    def isPrime(num: Long): Boolean = {
      num match {
        case num if (num < 2) => false
        case _ => {
          2 to (sqrt(num) toInt) forall (num % _ != 0)
        }
      }
    }

    // if a Long is a prime print it in console
    def printIfIsPrime(num: Long) = {
      if (isPrime(num))
        println(num)
    }

    // get range
    def getInput(times: Int) = {
      for (input <- 0 until times) yield {
        val range = readLine().split(" ")
       (range(0) toLong, range(1) toLong)
      }
    }

    val ranges = getInput(readInt())
    for (time <- 0 until ranges.length) {
      (ranges(time)._1 to ranges(time)._2).foreach(printIfIsPrime(_))
      if (time != ranges.length - 1)
        println()
    }

  }
}

当我在SPOJ中运行我的代码时,我得到了一个结果:time limit exceeded

我需要让我的代码更有效率,你能帮助我吗?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

isPrime可以用较低级别的风格编写。您还可以提高println方法的速度。

def main(args: Array[String]) {
  val out = new java.io.PrintWriter(System.out, false)

  def isPrime(n: Long): Boolean = {
    if(n <= 3) return n > 1
    else if(n%2 == 0 || n%3 == 0) return false
    else {
      var i = 5
      while(i*i <= n) {
        if(n%i == 0 || n%(i+2) == 0) return false
        i += 6
      }
      return true
    }
  }

  def printIfIsPrime(num: Long) = {
    if (isPrime(num)) {
      out.println(num)
    }
  }
  ...
  val ranges = getInput(readInt())
  for (time <- 0 until ranges.length) {
    (ranges(time)._1 to ranges(time)._2).foreach(printIfIsPrime(_))
    if (time != ranges.length - 1)
      out.println()
  }
  out.flush()
}