Created
September 15, 2012 14:01
-
-
Save digitalsonic/3728082 to your computer and use it in GitHub Desktop.
求某个范围内素数的个数
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
# 求某个范围内素数的个数 | |
# 最大值不要超过1亿 | |
def prime max_number | |
nums = Array.new(max_number + 1, 1) | |
sqrt_num = Math.sqrt(max_number).to_i | |
(4...max_number).step(2) { |n| nums[n] = 0 } | |
(3...sqrt_num).step(2) { |n| (n * 2...(max_number + 1)).step(n) { |m| nums[m] = 0 } if (nums[n] == 1) } | |
return nums.count(1) - 2 # 去掉nums[0]和nums[1] | |
end | |
#=========================================================== | |
# 以下是性能测试代码 | |
#=========================================================== | |
# 预热 | |
prime(10000) | |
# 评测 | |
require 'benchmark' | |
Benchmark.bm do |x| | |
(4..8).each do |i| | |
x.report(10**i){ prime(10**i) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment