Created
September 11, 2008 04:27
-
-
Save karbassi/10159 to your computer and use it in GitHub Desktop.
Ruby class to return primes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Primes | |
attr_reader :primes | |
def initialize(len = nil) | |
return nil if len.nil? | |
state = Numeric.new | |
@primes = [2, 3] | |
i = 4 | |
count = 0 | |
while count < len.abs - 2 | |
(2..(Math.sqrt(i).ceil)).each do | |
|x| | |
state = true | |
if (i.divmod(x)[1] == 0) | |
state = false | |
break | |
end | |
end | |
if state | |
@primes << i | |
count +=1 | |
end | |
i += 1 | |
end | |
return @primes | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'primes.rb' | |
p = Primes.new(10) | |
puts p.primes | |
# Output | |
# ------ | |
# 2 | |
# 3 | |
# 5 | |
# 7 | |
# 11 | |
# 13 | |
# 17 | |
# 19 | |
# 23 | |
# 29 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment