S-99を解く。
素因数分解
class IntWrapper(n:scala.Int) { def isPrime(n:Int): Boolean = (n != 1) && (List.range(2,math.sqrt(n).toInt+1) forall (i => n % i != 0)) def sieve(s: Stream[Int]): Stream[Int] = Stream.cons(s.head, sieve(s.tail filter (_ % s.head != 0))) val ps = sieve(Stream.from(2)) def primeFactors: List[Int] = { def primeFactorsR(n: Int, ps: Stream[Int]): List[Int] = if (isPrime(n)) List(n) else if (n % ps.head == 0) ps.head :: primeFactorsR(n / ps.head, ps) else primeFactorsR(n, ps.tail) primeFactorsR(n, ps) } } implicit def int2IntWrapper(n:scala.Int) = new IntWrapper(n) println("s35: " + 315.primeFactors)
エラトステネスの篩はここを参考にした。
Streamを使うと
def sieve(s: Stream[Int]): Stream[Int] = Stream.cons(s.head, sieve(s.tail filter (_ % s.head != 0))) val ps = sieve(Stream.from(2))
とHaskellのように書ける