Last active
April 19, 2018 04:59
-
-
Save komasaru/5180084 to your computer and use it in GitHub Desktop.
Ruby script to compute factorials.
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 | |
#********************************************* | |
# 階乗計算(1! - 49! 各 64 桁) | |
#********************************************* | |
# | |
class CalcFactorial | |
L = 64 # 計算桁数 | |
L2 = (L + 7 ) / 8 # 配列サイズ | |
N = 49 # 計算個数 | |
# 計算・結果出力 | |
def calc | |
s = Array.new(L2, 0) | |
s[-1] = 1 | |
1.upto(N) do |k| | |
s = long_mul(s, k) | |
printf("%2d!=", k) | |
display(s) | |
end | |
rescue => e | |
raise | |
end | |
private | |
# ロング * ショート | |
def long_mul(a, b) | |
z = Array.new(L2, 0) | |
carry = 0 | |
(L2 - 1).downto(0) do |i| | |
w = a[i] | |
z[i] = (w * b + carry) % 100000000 | |
carry = (w * b + carry) / 100000000 | |
end | |
return z | |
rescue => e | |
raise | |
end | |
# 結果出力 | |
def display(s) | |
0.upto(L2 - 1) do |i| | |
printf("%08d", s[i]) | |
end | |
printf("\n") | |
rescue => e | |
raise | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = CalcFactorial.new | |
# 階乗計算 | |
obj.calc | |
rescue => e | |
$stderr.puts "[#{e.class}] #{e.message}\n" | |
e.backtrace.each{ |tr| $stderr.puts "\t#{tr}" } | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment