Skip to content

Instantly share code, notes, and snippets.

@pokutuna
Created September 9, 2012 12:03
Show Gist options
  • Save pokutuna/3683998 to your computer and use it in GitHub Desktop.
Save pokutuna/3683998 to your computer and use it in GitHub Desktop.
def isPrime(n: Int): Boolean = (2 to math.sqrt(n).toInt).forall(n % _ != 0)
val groupedPrimes= Stream.from(2).filter(isPrime).dropWhile(_ < 1000).takeWhile(_ < 10000).toList.groupBy(_.toString.sortWith(_ < _))
def findArithmeticProgression(nums: List[Int]): Option[List[Int]] = {
@annotation.tailrec
def rec(h: Int, tail: List[Int]): Option[List[Int]] = {
if (tail.length < 2) return None
tail.find( n => tail.contains(n + (n - h)) ) match {
case Some(n) => return Some(List(h, n, n + (n - h)))
case None => rec(tail.head, tail.tail)
}
}
rec(nums.head, nums.tail)
}
val result = groupedPrimes.values.map(findArithmeticProgression).collectFirst{ case Some(n) => n }
println(result.get.mkString) // => 296962999629
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment