Last active
December 4, 2017 02:52
-
-
Save komasaru/5106587 to your computer and use it in GitHub Desktop.
Ruby script to compute big-digit values.
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 CalcBigDigits | |
# 配列サイズ | |
N = 5 | |
def initialize | |
# 計算する数字(a, b: 加減算用、c, d: 剰除算用) | |
@a = [56789012,34567890,12345678,90123456,78901234] | |
@b = [12345678,90123456,78901234,56789012,34567890] | |
@c = [ 12,34567890,12345678,90123456,78901234] | |
@d = 99 | |
end | |
# 計算・結果出力 | |
def calc | |
long_add # ロング + ロング | |
long_sub # ロング - ロング | |
long_mul # ロング * ショート | |
long_div # ロング / ショート | |
end | |
# ロング + ロング | |
def long_add | |
# 計算 | |
@z = Array.new(N, 0) | |
carry = 0 | |
(N - 1).downto(0) do |i| | |
@z[i] = @a[i] + @b[i] + carry | |
if @z[i] < 100000000 | |
carry = 0 | |
else | |
@z[i] = @z[i] - 100000000 | |
carry = 1 | |
end | |
end | |
# 結果出力 | |
print " " | |
display_l(@a) | |
print "+" | |
display_l(@b) | |
print "=" | |
display_l(@z) | |
print "\n" | |
end | |
# ロング - ロング | |
def long_sub | |
# 計算 | |
@z = Array.new(N, 0) | |
borrow = 0 | |
(N - 1).downto(0) do |i| | |
@z[i] = @a[i] - @b[i] - borrow | |
if @z[i] >= 0 | |
borrow = 0 | |
else | |
@z[i] += 100000000 | |
borrow = 1 | |
end | |
end | |
# 結果出力 | |
print " " | |
display_l(@a) | |
print "-" | |
display_l(@b) | |
print "=" | |
display_l(@z) | |
print "\n" | |
end | |
# ロング * ショート | |
def long_mul | |
# 計算 | |
@z = Array.new(N, 0) | |
carry = 0 | |
(N - 1).downto(0) do |i| | |
w = @c[i] | |
@z[i] = (w * @d + carry) % 100000000 | |
carry = (w * @d + carry) / 100000000 | |
end | |
# 結果出力 | |
print " " | |
display_l(@c) | |
print "*" | |
display_s(@d) | |
print "=" | |
display_l(@z) | |
print "\n" | |
end | |
# ロング / ショート | |
def long_div | |
# 計算 | |
@z = Array.new(N, 0) | |
remainder = 0 | |
0.upto(N - 1) do |i| | |
w = @c[i] | |
@z[i] = (w + remainder) / @d | |
remainder = ((w + remainder) % @d) * 100000000 | |
end | |
# 結果出力 | |
print " " | |
display_l(@c) | |
print "/" | |
display_s(@d) | |
print "=" | |
display_l(@z) | |
print "\n" | |
end | |
# 結果出力(ロング用) | |
def display_l(s) | |
0.upto(N - 1) {|i| printf(" %08d", s[i])} | |
print "\n" | |
end | |
# 結果出力(ショート用) | |
def display_s(s) | |
0.upto(N - 2) {|i| printf(" %8s", " ")} | |
printf(" %08d\n", s) | |
end | |
end | |
# メイン処理 | |
begin | |
# 計算クラスインスタンス化 | |
obj = CalcBigDigits.new | |
# 多桁計算 | |
obj.calc | |
rescue => e | |
$stderr.puts "[例外発生] #{e}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment