Drkcore

04 10 2011 Scala Tweet

Ninety-Nine Scala Problems (P35)

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のように書ける

ProductName Scalaスケーラブルプログラミング第2版
Martin Odersky
インプレスジャパン / 4830円 ( 2011-09-27 )


About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021