diff options
author | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2016-08-10 18:17:41 +0000 |
---|---|---|
committer | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2016-08-10 18:17:41 +0000 |
commit | 2401c512ef2e7ad90b133d18960b9279b9417eb8 (patch) | |
tree | 71ee28418860cd687dad0d7632f71e6f4b8091c8 /lib | |
parent | 3433653240499b62751d2cea7dd61f082b82f1c7 (diff) | |
download | ruby-2401c512ef2e7ad90b133d18960b9279b9417eb8.tar.gz |
* lib/prime.rb: Optimize prime?
Adapted from patch by Jabari Zakiya [#12665]
* test/test_prime.rb: Improve test
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@55856 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib')
-rw-r--r-- | lib/prime.rb | 11 |
1 files changed, 6 insertions, 5 deletions
diff --git a/lib/prime.rb b/lib/prime.rb index c64c0c2cf1..a6700e3e8b 100644 --- a/lib/prime.rb +++ b/lib/prime.rb @@ -33,11 +33,12 @@ class Integer # Returns true if +self+ is a prime number, else returns false. 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 + return true if self == 5 + return false unless 30.gcd(self) == 1 + (7..Math.sqrt(self).to_i).step(30) do |p| + return false if + self%(p) == 0 || self%(p+4) == 0 || self%(p+6) == 0 || self%(p+10) == 0 || + self%(p+12) == 0 || self%(p+16) == 0 || self%(p+22) == 0 || self%(p+24) == 0 end true end |