Project Euler 001

Question

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.

Answer

1
233168

C

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

int main(int argc, char **argv)
{
int sum = 0;
for (int i = 0; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
printf("%d\n", sum);
return 0;
}

Java

1
2
3
4
5
6
7
// This forces every solution class to implement a common interface,
// which is helpful for unit testing like in the EulerTest implementation.
public interface EulerSolution {

public String run();

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public final class p001 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p001().run());
}


/*
* Computers are fast, so we can implement this solution directly without any clever math.
* A conservative upper bound for the sum is 1000 * 1000, which fits in a Java int type.
*/
public String run() {
int sum = 0;
for (int i = 0; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0)
sum += i;
}
return Integer.toString(sum);
}

}

Mathematica

1
Total[Select[Range[999], Function[x, Mod[x, 3] == 0 || Mod[x, 5] == 0]]]

Python

1
2
#!/usr/bin/env python
print(sum(i for i in range(1000) if (i % 3 == 0) or (i % 5 == 0)))

JavaScript

1
2
3
4
5
6
7
let s = 0
for (var i = 1; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
s += i
}
}
console.log(s)

Ruby

1
2
3
4
5
6
7
8
#!/usr/bin/env ruby
sum = 0
1000.times do |i|
if i % 3 == 0 or i % 5 == 0
sum += i
end
end
puts sum

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
sum := 0
for i := 0; i < 1000; i++ {
if i%3 == 0 || i%5 == 0 {
sum += i
}
}
fmt.Println(sum)
}

Haskell

1
2
main ::  IO ()
main = print $ sum [n | n <- [1..999], or [(n `mod` 3 == 0), (n `mod` 5 == 0)]]

Clojure

1
2
3
4
5
#!/usr/bin/env clojure
(defn multiple? [n]
(or (= (rem n 3) 0) (= (rem n 5) 0)))

(println (reduce + (filter multiple? (range 1000))))

Scheme

1
2
3
4
5
6
7
(display
(reduce + 0
(filter
(lambda (n)
(or (= (remainder n 3) 0) (= (remainder n 5) 0)))
(iota 1000))))
(newline)
文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/02/08/Project-Euler-001/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏