marlonmisra - 7 months ago 36

Ruby Question

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 'Prime.new' 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 = Prime.new

primes = [ primer.next ]

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 << primer.next

end

primes.each do |i|

count = 0

while n % i == 0

n = n / i

count += 1

end

if count > 0

total *= count + 1

end

end

total

end

while(count_prime_factors(primer, primes, n) < seed)

n += i

i += 1

end

puts n

Answer

Try replacing `Prime.new`

with `Prime.instance`

and each instance of `primes.next`

with `primes.succ`

.

See the source code for the `Prime`

class. You will find that `Prime.next`

is aliased to `Prime.succ`

but `Prime.next`

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.