Skip to content

Instantly share code, notes, and snippets.

@zerosum
Created February 20, 2013 11:58
Show Gist options
  • Select an option

  • Save zerosum/4995021 to your computer and use it in GitHub Desktop.

Select an option

Save zerosum/4995021 to your computer and use it in GitHub Desktop.
Project Euler: Problem 7
package object Prime {
def primes(from: Int, to: Int): Stream[Int] = Number
.from(from)
.takeWhile(_ <= to - from + 1)
.filter(n => n != 1 && Divisors
.getDivisors(n)
.filterNot(_ == 1)
.isEmpty)
}
package object Divisors {
/**
* 自身を除くnの約数を返す。
* 約数は昇順にソートされる。
*
* @param n
* @return
*/
def getDivisors(n: Int): Stream[Int] = {
val divs = Number.from(1).take(math.sqrt(n).toInt).filter(n % _ == 0)
(divs ++ divs.map(n / _).filterNot(divs.contains(_))).filterNot(_ == n).sortWith(_ < _)
}
}
package object Number {
/**
* n以上の整数の無限数列を生成する
*
* @param n
* @return
*/
def from(n: Int): Stream[Int] = n #:: from(n + 1)
def everyTwoFrom(n: Int): Stream[Int] = n #:: from(n + 2)
}
package euler.zerosum
import euler.zerosum.Prime._
object Euler0007 {
def main(args: Array[String]) {
println(primes(1, 110000).take(10001).last)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment