Created
January 20, 2013 16:33
-
-
Save zerosum/4579675 to your computer and use it in GitHub Desktop.
Project Euler: Problem 10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package euler.zerosum { | |
package object Sieve { | |
/** | |
* Int型エラトステネスの篩 | |
*/ | |
def sieveInt(numbers: List[Int]): List[Int] = { | |
sieveInt(numbers, Nil) | |
} | |
private def sieveInt(numbers: List[Int], primes: List[Int]): List[Int] = { | |
if(primes.nonEmpty && Math.pow(primes.last, 2) > numbers.last) { | |
primes ::: numbers | |
} else { | |
val h = numbers.head | |
sieveInt(numbers.tail.filter(_%h != 0), primes ::: h :: Nil) | |
} | |
} | |
/** | |
* Long型エラトステネスの篩 | |
*/ | |
def sieveLong(numbers: List[Long]): List[Long] = { | |
sieveLong(numbers, Nil) | |
} | |
private def sieveLong(numbers: List[Long], primes: List[Long]): List[Long] = { | |
if(primes.nonEmpty && Math.pow(primes.last, 2) > numbers.last) { | |
primes ::: numbers | |
} else { | |
val h = numbers.head | |
sieveLong(numbers.tail.filter(_%h != 0), primes ::: h :: Nil) | |
} | |
} | |
} | |
package object Time { | |
def printExecuteTime(proc: => Unit) = { | |
val start = System.currentTimeMillis | |
proc | |
println((System.currentTimeMillis - start) + " msec") | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* $ scalac -cp . euler.scala Euler0010.scala | |
* $ scala Euler0010 <arg: Int> | |
*/ | |
import euler.zerosum.Sieve._ | |
import euler.zerosum.Time._ | |
object Euler0010 { | |
private def execute(max: Long): Long = { | |
sieveLong((2L to max).toList).sum | |
} | |
def main(args: Array[String]) { | |
printExecuteTime { | |
println(execute(args(0).toLong)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment