!Mac OS X-10.15.7 !ruby-2.6.3p62
課題内容
自然対数の底e(200桁まで)の値で連続10桁で最初の素数を求める.以下をexp.txtとして入力として使用する.
2.71828182845904523536028747135266249775
7247093699959574966967627724076630353547
5945713821785251664274274663919320030599
2181741359662904357290033429526059563073
81323286279434907632338298807531952510190
方針
素数を特定するために, 以下サイトを参考にした.https://qiita.com/evendemiaire/items/f7069a77b7432a3622a3
コード
# require './aeroc'
require 'prime'
require 'colorize'
def puts_vals(expected, result)
puts "expected :: #{expected}"
puts "result :: #{result}"
end
def assert_equal(expected, result)
puts_vals(expected, result)
print case expected == result
when true ; "succeeded in #{__method__}.\n".green
when false ; "failed in #{__method__}.\n".red
end
end
def check(num)
2.step(to: Math.sqrt(num), by: 1) do |i|
return false if num%i==0
true
end
end
def read_exp(path)
exp = File.read(path).delete(".")
return exp
end
def exp_check(exp)
0.step(to: exp.length-10, by: 1) do |i|
num = exp[i..i+10-1].to_i
if check(num)
result = num
end
if Prime.prime?(num)
assert_equal(num,result)
break
end
end
end
if $PROGRAM_NAME == __FILE__
exp = read_exp("exp.txt")
exp_check(exp)
end
参考サイト
- https://qiita.com/daddygongon/items/ba94b0f2a73990fc6a07
- https://qiita.com/evendemiaire/items/f7069a77b7432a3622a3
- https://qiita.com/musutafakemaru/items/872870c52b170d510309
- source ~/my_ruby/grad_members_20f/members/drop-sd/lectures/ex_google.org