Skip to content

Instantly share code, notes, and snippets.

@giuan
Created February 6, 2016 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giuan/f2176226e253d8620e0a to your computer and use it in GitHub Desktop.
Save giuan/f2176226e253d8620e0a to your computer and use it in GitHub Desktop.
prime?
require 'prime'
require 'benchmark'
def isqrt(n)
n = n.to_i
x = n
y = (x + 1) / 2
while y < x
x = y
y = (x + n / x) / 2
end
x
end
def prime? (n)
return false if n<1
return true if [2,3].include?(n)
return false if n % 2 == 0 || n % 3 == 0
i = 1
x = 6
n_2 = isqrt(n)
while (x <= n_2)
return false if n % (x-1) == 0 || n % (x+1) == 0
i += 1
x = 6*i
end
true
end
n = 1090109110921093
Benchmark.bm do |r|
10.times do
r.report {puts n.prime?}
r.report {puts prime?(n)}
end
end
@jzakiya
Copy link

jzakiya commented Feb 8, 2016

This is the version of prime? in prime.rb used in 2.3.0.

class Integer
      def prime?
        return self >= 2 if self <= 3
        return false if self % 2 == 0 or self % 3 == 0
        (5..(self**0.5).floor).step(6).each do |i|
          if self % i == 0 || self % (i + 2) == 0
            return false
          end
        end
        true
      end
end

For the math behind this see the primes-utils rubygem, and its PRIMES-UTILS HANDBOOK.

https://www.scribd.com/doc/266461408/Primes-Utils-Handbook

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment