ONLY DO WHAT ONLY YOU CAN DO

こけたら立ちなはれ 立ったら歩きなはれ

Scala で Project Euler Problem 3

13195 の素因数は 5, 7, 13, 29 である.

600851475143 の素因数のうち最大のものを求めよ.

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

scala> def max_factor(n: Int, factor: Int = 2): Int = {
     |     if      (n          <  factor * factor) n
     |     else if (n % factor == 0              ) max_factor(n / factor, factor    )
     |     else                                    max_factor(n         , factor + 1)
     | }
max_factor: (n: Int,factor: Int)Int

scala> max_factor(8)
res0: Int = 2

scala> max_factor(9)
res1: Int = 3

scala> max_factor(13195)
res2: Int = 29

scala> max_factor(600851475143)
<console>:1: error: integer number too large
       max_factor(600851475143)
                  ^

scala> def max_factor(n: Long, factor: Long = 2): Long = {
     |     if      (n          <  factor * factor) n
     |     else if (n % factor == 0              ) max_factor(n / factor, factor    )
     |     else                                    max_factor(n         , factor + 1)
     | }
max_factor: (n: Long,factor: Long)Long

scala> max_factor(600851475143)
<console>:1: error: integer number too large
       max_factor(600851475143)
                  ^

scala> max_factor(600851475143L)
res3: Long = 6857

scala>
scala> def factor_list(n: Long, factor: Long = 2): List[Long] = {
     |     if      (n          <  factor * factor) List(n)
     |     else if (n % factor == 0              ) factor::factor_list(n / factor, factor    )
     |     else                                            factor_list(n         , factor + 1)
     | }
factor_list: (n: Long,factor: Long)List[Long]

scala> factor_list(13195)
res0: List[Long] = List(5, 7, 13, 29)

scala> factor_list(600851475143L)
res1: List[Long] = List(71, 839, 1471, 6857)