gist: 686 Download_button fork
public
Public Clone URL: git://gist.github.com/686.git
prime1.rb
1
2
3
4
5
6
7
8
9
10
# Calculate all the primes between 0 and the value specified
def primes(up_to)
  prev = []
  (2..up_to).select do |x|
    max_p = Math.sqrt(x).truncate
    if !prev.find { |y| y <= max_p ? x % y == 0 : break }
      prev << x
    end
  end
end
prime2.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
require 'mathn'
class Fixnum
  # Return true if self is a prime number
  def prime?
    max = Math.sqrt(self).ceil
    max -= 1 if max % 2 == 0
    pgen = Prime.new
    pgen.each do |factor|
      return false if self % factor == 0
      return true if factor > max
    end
  end
end
prime3.rb
1
2
3
4
5
6
7
# Slower than prime2
class Fixnum
  # Return true if self is a prime number
  def prime?
    ('1' * self) !~ /^1?$|^(11+?)\1+$/
  end
end
prime4.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
32
33
# http://www.rubyinside.com/using-rubyinline-to-speed-up-code-by-10x-159.html
require "rubygems"
require "inline"
 
class Primes
  inline do |builder|
    builder.c '
int prime(int num) {
int x;
for (x = 2; x < (num - 1) ; x++) {
if (num == 2) {
return 1;
}
if (num % x == 0) {
return x;
}
}
return 1;
}'
  end
end
 
p = Primes.new
 
for num in 2..10_000 do
  is_prime = p.prime(num)
  if is_prime == 1
    puts "#{num} is a prime number"
  else
    puts "#{num} equals #{is_prime} * #{num/is_prime}"
  end
end
 

Owner

robolson

Revisions