Last active
January 21, 2016 09:52
-
-
Save tanishiking/476cb598db8ebca1fe42 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
object problem50 { | |
def getMaxSumOfPrimes(limit: Int): Option[Int] = { | |
// 1000000以下の素数の遅延リスト | |
lazy val primes: Stream[Int] = Stream.cons(2, Stream.from(3).filter(i => primes.takeWhile(j => j * j <= i).forall(i % _ > 0))).takeWhile(_ <= limit) | |
def isPrime(num: Int): Boolean = primes.contains(num) | |
// 素数を小さい順に足していって1000000以下で最大となるまでの素数の遅延リスト | |
val primeSumLimit: List[Int] = primes.takeWhile(i=> primes.takeWhile(_ <= i).map(_.toLong).sum <= limit).toList | |
for (span <- primeSumLimit.length to 1 by -1) { | |
if (primeSumLimit.sliding(span).map(_.sum).exists(isPrime)) { | |
return Some(primeSumLimit.sliding(span).map(_.sum).filter(isPrime).max) | |
} | |
} | |
None | |
} | |
def main(args: Array[String]): Unit = { | |
val limit = 1000000 | |
getMaxSumOfPrimes(limit) match { | |
case Some(sum) => println(sum) | |
case None => println("Not found...") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment