S
Sam Kong
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?
Sam
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?
Sam