010 Summation of primes -- v2.sf 643 B

12345678910111213141516171819202122232425262728293031323334
  1. #!/usr/bin/ruby
  2. # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
  3. # Find the sum of all the primes below two million.
  4. # https://projecteuler.net/problem=10
  5. # Runtime: 1.138s
  6. func sum_of_primes(n) {
  7. return 0 if (n <= 1)
  8. var r = n.isqrt
  9. var V = (1..r -> map {|k| idiv(n,k) })
  10. V << range(V.last-1, 1, -1).to_a...
  11. var S = Hash(V.map{|k| (k, faulhaber(k,1)) }...)
  12. for p in (2..r) {
  13. S{p} > S{p-1} || next
  14. var sp = S{p-1}
  15. var p2 = p*p
  16. V.each {|v|
  17. break if (v < p2)
  18. S{v} -= p*(S{idiv(v,p)} - sp)
  19. }
  20. }
  21. return S{n}-1
  22. }
  23. say sum_of_primes(2e6)