karbassi (owner)

Revisions

gist: 10159 Download_button fork
public
Description:
Ruby class to return primes.
Public Clone URL: git://gist.github.com/10159.git
Embed All Files: show embed
primes.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
run.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require 'primes.rb'
 
p = Primes.new(10)
puts p.primes
 
# Output
# ------
# 2
# 3
# 5
# 7
# 11
# 13
# 17
# 19
# 23
# 29