Ruby script to compute prime factorizatiton.
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
#! /usr/local/bin/ruby | |
#======================================= | |
# 素因数分解 | |
#======================================= | |
class PrimeFactorization | |
# 素因数分解 | |
def decomposit_prime(n) | |
# 割る数の初期値 | |
a = 2 | |
# √n ≧ a ( n ≧ a * a ) の間ループ処理 | |
while n >= a * a | |
# a で割り切れたら、a は素因数 | |
# そして、割られる数を a で割る | |
# a で割り切れなかったら a を 1 増加させる | |
if n % a == 0 | |
print "#{a} * " | |
n /= a | |
else | |
a += 1 | |
end | |
end | |
# 最後に残った n は素因数 | |
puts n | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = PrimeFactorization.new | |
while true | |
# データ入力 | |
print "自然数 ( 0 : 終了 ):" | |
int_num = gets.chomp.to_i | |
break if int_num < 1 | |
# 素因数分解 | |
obj.decomposit_prime(int_num) | |
end | |
rescue => e | |
puts "[例外発生] #{e}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment