Last active
August 29, 2015 14:09
-
-
Save sandyxu/7e1ba796932cf6af9c42 to your computer and use it in GitHub Desktop.
素数算法比较,使用Benchmark进行测试。
This file contains hidden or 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 'benchmark' | |
# 遍历N是否能被从2到sqrt(N)之间的素数整除。若不能则为素数 | |
def fast(max) | |
mini = Math.sqrt(max).to_i | |
sub_primes = sub_primes(mini) | |
sub_primes + ((mini+1)..max).select{|n| sub_primes.all?{|obj| n % obj > 0 } } | |
end | |
def sub_primes(sub) | |
(2..sub).select{ |n| is_prime(n) } | |
end | |
# | |
def slow(max) | |
(2..max).select{|n| is_prime(n) } | |
end | |
# 判断一个数是否为素数 | |
# N是否能被 2到(N+1)/2之间的整数 整除 | |
def is_prime(n) | |
(2..(n+1)/2).all?{ |d| n % d > 0} | |
end | |
Benchmark.bm do |x| | |
x.report("fast:") { fast(10000) } | |
x.report("slow:") { slow(10000) } | |
end | |
# 测试环境:OS X Yosemite 10.10 / 2.6GHz Intel Core i5 / 8GB/SSD | |
# ruby 2.1.3p242 | |
#测试结果如下: | |
# | |
# user system total real | |
# fast: 0.010000 0.000000 0.010000 ( 0.009058) | |
# slow: 0.250000 0.000000 0.250000 ( 0.251279) | |
# 根据 “[哪个算法是判断一个数是否为素数的最简单算法?](http://www.zhihu.com/question/26477210)” 写的测试 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment