ScalaでProject Euler(65)

Problem 36

10進の回文数を生成して2進の回文数になっているかを調べます。

def pow(n :Int, e :Int) :Int =
    if(e == 0)
        1
    else {
        val m = pow(n, e / 2)
        if(e % 2 == 1)
            m * m * n
        else
            m * m
    }

def palindrome(n :Int, start :Int = 1) :Iterator[Int] = n match {
    case 0 => Iterator(0)
    case 1 => Iterator.range(start, 10)
    case _ => {
        val f = pow(10, n - 1) + 1
        for(d <- Iterator.range(start, 10); m <- palindrome(n - 2, 0))
            yield d * f + m * 10
    }
}

def binary(n :Int) :Iterator[Int] =
    if(n == 0) Iterator() else Iterator(n & 1) ++ binary(n >> 1)

def number(it :Iterator[Int]) =
    it.foldLeft(0)((x, y) => (x << 1) | y)

val N = 6
val it = Iterator.range(1, N + 1).flatMap(n => palindrome(n))
println (it.filter(n => number(binary(n)) == n).sum)