Problem 10
Ruby
1def sum_primes_in_range(num, max)
2 sum = 0
3 loop do
4 if num > max
5 break
6 end
7 prime = true;
8 temp = 2;
9 while temp <= Math.sqrt(num)
10 if num % 2 == 0
11 prime = false;
12 break;
13 end
14 if num % temp == 0
15 prime = false;
16 break;
17 end
18 temp += 1
19 end
20 if prime == true
21 sum += num
22 end
23 num += 1;
24 end
25 sum
26end
27
28a, b, c, d, e, f, g, h= [
29 Thread.new{sum_primes_in_range(2, 250000)},
30 Thread.new{sum_primes_in_range(250000, 500000)},
31 Thread.new{sum_primes_in_range(500000, 750000)},
32 Thread.new{sum_primes_in_range(750000, 1000000)},
33 Thread.new{sum_primes_in_range(1000000, 1250000)},
34 Thread.new{sum_primes_in_range(1250000, 1500000)},
35 Thread.new{sum_primes_in_range(1500000, 1750000)},
36 Thread.new{sum_primes_in_range(1750000, 2000000)}
37].map(&:join).map(&:value)
38sum_primes = a + b + c + d + e + f + g + h;
39puts"#{sum_primes}"
Perl6
1say [+] (1 ... ^ 2_000_000).hyper.grep({is-prime($_)});
1(ns problem10.core)
2
3(defn is-prime?
4 [x]
5 (if (= x 0) false
6 (loop [iter 2 top (int (Math/sqrt x))]
7 (if (> iter top)
8 true
9 (if (= 0 (mod x iter))
10 false
11(recur (inc iter) top))))))
12
13(defn -main
14 []
15 (println (reduce + (filter is-prime? (range 2000000)))))