Skip to content

Instantly share code, notes, and snippets.

@a7madM
Created February 21, 2019 14:28
Show Gist options
  • Select an option

  • Save a7madM/b254164097aaa37e14c6fb08cd80db5a to your computer and use it in GitHub Desktop.

Select an option

Save a7madM/b254164097aaa37e14c6fb08cd80db5a to your computer and use it in GitHub Desktop.
Primes Ruby
class Primes
def prime?(n)
return false if n < 2
max = Math.sqrt(n).floor
(2..max).none? { |k| (n % k).zero? }
end
def below(limit)
primes = [2]
primes += (3..limit).step(2).select { |i| prime?(i) }
primes
end
def summation(limit)
primes = below(limit)
primes.inject(:+)
end
def sum_most_consecutive(limit)
primes = below(limit)
max_sum = 0
max_index = -1
primes_count = primes.count
0.upto(primes_count - 1) do |i|
sum = 0
i.upto(primes_count - 1) do |j|
sum += primes[j]
break if sum > limit
if prime?(sum) && sum > max_sum && j - i > max_index
max_index = j - 1
max_sum = sum
end
end
end
max_sum
end
end
# uncomment these lines if you want to execute and see measures.
# require 'benchmark'
# primes = Primes.new
# puts Benchmark.measure { primes.summation(2_000_000) }
# copy this file in directory named spec
# make sure that ruby is installed, and rspec gem also
# rspec => https://github.com/rspec/rspec
# in terminal => run this command $ rspec .
require_relative '../primes'
describe Primes do
it 'Primes Summation under 10' do
primes = Primes.new
expect(primes.summation(10)).to eq(17)
end
it 'Primes Summation under 100' do
primes = Primes.new
expect(primes.summation(100)).to eq(1060)
end
# the most important one :D
it 'Primes Summation under 2000000' do
primes = Primes.new
expect(primes.summation(2_000_000)).to eq(142_913_828_922)
end
it 'Prime that equals Summation of Most Consecutive Primes under 10' do
primes = Primes.new
expect(primes.sum_most_consecutive(10)).to eq(5)
end
it 'Prime that equals Summation of Most Consecutive Primes under 1000' do
primes = Primes.new
expect(primes.sum_most_consecutive(1000)).to eq(953)
end
it 'Prime that equals Summation of Most Consecutive Primes under 1000000' do
primes = Primes.new
expect(primes.sum_most_consecutive(1_000_000)).to eq(997_651)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment