This program calculates nth prime in ruby
primes.rb
630 B
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def isDivisibe(candidate, by)
candidate % by == 0
end
def isPrimeDivisible(primes, candidate, count)
for e in (0...count)
return false if Math.sqrt(candidate) < primes[e]
return true if isDivisibe(candidate, primes[e])
end
false
end
def countPrimes(size)
primes = Array.new(size)
count = 0
candidate = 2
while count < size
unless isPrimeDivisible(primes, candidate, count)
primes[count] = candidate
count += 1
end
candidate += 1
end
primes[size - 1]
end
for count in Array.[](25_000, 50_000, 100_000)
result = countPrimes count
puts "#{count}th prime no is #{result}"
end