On 8/7/06, Sam Kong <sam.s.kong / gmail.com> wrote:
> Hello!
>
>
> Here's my code.
>
> ---------------------
> class Integer
>     def prime?
>         return false if self < 2
>         return @is_prime if @prime_cached
>         @prime_cached = true
>         (2..(self ** 0.5)).each do |i|
>             return (@is_prime = false) if i.prime? and self % i == 0
>         end
>         @is_prime = true
>     end
> end
> ---------------------
>
> I want each integer to remember if it's a prime number or not.
> As the calculation uses cache of smaller prime numbers, it runs fast.
> But I'm not sure if the cache is preserved after GC runs (when nothing
> refers to the integers).
> If the cache is not preserved, it's no use.
>
> My first idea was keeping the cache in a class variables like
> @@prime_numbers and @@max_cached.
> But I think it would be better if each object remembers its own state.
>
> What do you think?

I'm pretty sure that your concern about GC is moot, but just as long
as you stay with in the range of Fixnums.  Fixnums are 'immediate'
objects, and never get collected. I Bignums are another matter.

For Fixnums your code works as is.  The @prime_cached iv is not needed
however, here's another way to do it:

class Integer
        def prime?
                return false if self < 2
                return @is_prime unless @is_prime.nil?
                (2..self**0.5).each do | i |
                        return (@is_prime = false) if i.prime? and self % i == 0
                end
                @is_prime = true
        end
end

-- 
Rick DeNatale

IPMS/USA Region 12 Coordinator
http://ipmsr12.denhaven2.com/

Visit the Project Mercury Wiki Site
http://www.mercuryspacecraft.com/