Skip to content

Instantly share code, notes, and snippets.

@pokutuna
Created September 10, 2012 02:38
Show Gist options
  • Save pokutuna/3688512 to your computer and use it in GitHub Desktop.
Save pokutuna/3688512 to your computer and use it in GitHub Desktop.
def isPrime(n: Int): Boolean = (2 to math.sqrt(n).toInt).forall(n % _ != 0)
val primes: Stream[Int] = Stream.from(2).filter(isPrime)
def primeProgressionLength(prime: Int, progression: Stream[Int] = primes): Option[Int] = {
def sumLength(max: Int, seq: Seq[Int], sum: Int = 0, len: Int = 0): Option[Int] = {
if (sum > max) return None
if (sum == max) return Some(len)
sumLength(max, seq.tail, sum + seq.head, len + 1)
}
if (progression.head >= (prime / 2)) return None
sumLength(prime, progression) match {
case Some(n) => return Some(n)
case None => primeProgressionLength(prime, progression.tail)
}
}
val result = primes.takeWhile(_ < 1000000).map( p => p -> primeProgressionLength(p).getOrElse(0)).maxBy(_._2)
println(result) // => (997651,543)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment