ONLY DO WHAT ONLY YOU CAN DO

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

Scala で Project Euler Problem 1

3か5の倍数になっている1000未満の自然数を足し合わせよ

10未満の自然数のうち, 3 もしくは 5 の倍数になっているものは 3, 5, 6, 9 の4つがあり, これらの合計は 23 になる.

同じようにして, 1000 未満の 3 か 5 の倍数になっている数字の合計を求めよ.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Scala

単純に加算
scala> (1 to 9)
res0: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> (1 to 9).filter(n => n % 3 == 0 || n % 5 == 0)
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 5, 6, 9)

scala> (1 to 9).filter(n => n % 3 == 0 || n % 5 == 0).sum
res2: Int = 23

scala> (1 to 999).filter(n => n % 3 == 0 || n % 5 == 0).sum
res3: Int = 233168

scala>

これが関数型プログラミングというやつか。
我ながらちょいと感動

等差数列の和
scala> def sn(a:Int, lim:Int) = {
     | val n = lim / a
     | val l = n * a
     | (a + l) * n / 2
     | }
sn: (a: Int,lim: Int)Int

scala> sn(3, 9)
res4: Int = 18

scala>  List(3, 5).map(sn(_, 999)).sum  - sn(15, 999)
res5: Int = 233168

scala>

ちょっと、中途半端...
List(3,5,15) に対しての処理にしたいところ

scala> def multiples_of_3_and_5(n:Int) = {
     |     if (n == 15) -sn(n, 999)
     |     else          sn(n, 999)
     | }
multiples_of_3_and_5: (n: Int)Int

scala> List(3, 5, 15).map(multiples_of_3_and_5).sum
res6: Int = 233168

scala>

等差数列の和

初項a、公差d の等差数列の初項から第n項 (末項 l=a+(n−1)d) までの和Snは