Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 19, 2018 04:29
Show Gist options
  • Save komasaru/c278208f4cc8f2561d96fa0d38b6c2a6 to your computer and use it in GitHub Desktop.
Save komasaru/c278208f4cc8f2561d96fa0d38b6c2a6 to your computer and use it in GitHub Desktop.
Ruby script to compute prime factorizatiton.
#! /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