Created
February 6, 2016 22:39
-
-
Save giuan/f2176226e253d8620e0a to your computer and use it in GitHub Desktop.
prime?
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 '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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is the version of
prime?
inprime.rb
used in 2.3.0.For the math behind this see the
primes-utils
rubygem, and itsPRIMES-UTILS HANDBOOK
.https://www.scribd.com/doc/266461408/Primes-Utils-Handbook