marlonmisra marlonmisra - 3 months ago 8x
Ruby Question is obsolete - how to rewrite this code?

This code finds the first prime number that has 500 divisors. When I run it it work, but I am told that "Prime::new is obsolete. use Prime::instance or class methods of Prime."

I thought this meant that I can replace '' with 'Prime.instance', but when I do that I'm told that 'next is an undefined method'. Since prime should be an enumerator, why am I getting this error? This right answer is 76576500.

require 'mathn'

primer =
primes = [ ]
seed = 500
n = (seed * (seed + 1)) / 2
i = seed + 1

def count_prime_factors primer, primes, n
total = 1
max = Math.sqrt(n).to_i

while primes.last < max
primes <<

primes.each do |i|
count = 0
while n % i == 0
n = n / i
count += 1
if count > 0
total *= count + 1


while(count_prime_factors(primer, primes, n) < seed)
n += i
i += 1

puts n


Try replacing with Prime.instance and each instance of with primes.succ.

See the source code for the Prime class. You will find that is aliased to Prime.succ but has no implementation itself. The behavior changes a bit depending on how you create an instance of Prime, which is why you get different errors above.