Skip to content

Instantly share code, notes, and snippets.

@imtiaz-emu
Created January 17, 2019 17:03
Show Gist options
  • Save imtiaz-emu/f36feafbfa79ba5272406c93e5af4ab6 to your computer and use it in GitHub Desktop.
Save imtiaz-emu/f36feafbfa79ba5272406c93e5af4ab6 to your computer and use it in GitHub Desktop.
Finology challenge: Sum of primes below 2 million and sum of consecutive prime below 1 million to be a prime.
'''
Problem 1
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17
Find the sum of all the primes below 2 million.
Problem 2
Which prime, below one million, can be written as the sum of the
most consecutive primes?
'''
class GenerateSolution
def sieve_of_eratosthenes(n)
primes = (0..n).to_a
primes[0] = primes[1] = nil
primes.each do |p|
next unless p
break if p * p > n
(p*p).step(n, p) { |m| primes[m] = nil }
end
primes.compact
end
def prime?(number)
return false if (number <= 1)
return true if (number <= 3)
return false if (number % 2 == 0 || number % 3 == 0)
i = 5
while (i*i < number)
return false if (number % i == 0 || number % (i+2) == 0)
i += 6
end
return true
end
def consecutive_prime_sum(primes, max_range)
max_sum = 0
max_no_of_primes = 0
for i in (0...primes.count)
for j in (i...primes.count)
sum, counter = primes[i..j].reduce(:+), j - i + 1
break if sum > max_range
if (prime?(sum)) && (max_no_of_primes < counter)
max_sum = sum
max_no_of_primes = counter
end
end
end
return max_sum
end
end
test1_max_range = 2000000
test2_max_range = 1000000
solution = GenerateSolution.new
start = Time.now
primes = solution.sieve_of_eratosthenes(test1_max_range)
puts "Sum of primes below #{test1_max_range} = #{primes.reduce(:+)}"
puts "The prime number below #{test2_max_range}, can be written as the sum of the most consecutive primes = #{solution.consecutive_prime_sum(primes, test2_max_range)}"
finish = Time.now
puts "Program excecution time = #{finish - start}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment