とんちゃんといっしょ

Cloudに関する技術とか日常とかについて書いたり書かなかったり

Problem 1

問題

Add all the natural numbers below one thousand that are multiples of 3 or 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.

http://projecteuler.net/index.php?section=problems&id=1
日本語

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

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

http://odz.sakura.ne.jp/projecteuler/index.php?Problem%201

解説

3か5で割り切れる数字を足すだけの簡単なお仕事。
RangeとArray#injectと三項演算子でショートコーディングしておいた。

ソースコード(Ruby)

p (3..999).inject{|s,i|(i%3<1||i%5<1)?s+i:s} 

ソースコード(Gauche)

(define (prob001 lis)
  (if (null? lis)
    0
    (if (or (= 0 (modulo (car lis) 3)) (= 0 (modulo (car lis) 5)))
    (+ (car lis) (prob001 (cdr lis)))
    (prob001 (cdr lis)))))

(use srfi-1)
(print (prob001 (iota 999 1)))