生物生産科学科 担当 國分 尚
プログラム8のtarget = 100
という部分を例えばtarget = 500
とすれば500番目の素数が求められる。
def sosuu?(x)
i = 3
while (i <= x/3) and (x % i != 0)
i = i + 2
end
if i > x/3
return true
else
return false
end
end
print "何番目の素数を求めますか? "
target = STDIN.gets.to_i
n = 3
c = 2
last = 2
while c <= target
if sosuu?(n)
last = n
c = c + 1
end
n = n + 2
end
print target, "th prime is ", last, ".\n"
上の解答例のprint ..., target = gets.to_i
の2行を以下のように書き換える。
target = ARGV[0].to_i
このようにすることで、コマンドラインからruby sosuu.rb 77と入力すると77番目の素数が得られる。
2004年5月14日作成、2006年4月8日更新
國分 尚