-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbig_integer.rb
78 lines (64 loc) · 1.8 KB
/
big_integer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class BigInteger
attr_reader :num_array
def initialize(num)
str_num = num.to_s
raise "invalid number" unless str_num.match(/^[0-9]*$/)
@num = str_num
@num_array = str_num.split("")
end
def +(other_bignum)
other_chars = other_bignum.num_array
if @num_array.length >= other_chars.length
apply_sum(@num_array, other_chars)
else
apply_sum(other_chars, @num_array)
end
end
def apply_sum(greater_num_arr, smaller_num_arr)
greater_num_arr = greater_num_arr.reverse
smaller_num_arr = smaller_num_arr.reverse
i = 0
result = ""
carry_over = 0
for i in 0..(greater_num_arr.length - 1) do
sum_val = smaller_num_arr[i].to_i + greater_num_arr[i].to_i + carry_over.to_i
if sum_val >= 10
new_val = sum_val % 10
carry_over = 1
result += new_val.to_s
else
carry_over = 0
result += sum_val.to_s
end
end
result += "1" if carry_over == 1
BigInteger.new(result.reverse)
end
def *(other)
i = BigInteger.new(0)
val_1 = BigInteger.new(1)
res = BigInteger.new(0)
while i.to_s != @num.to_s do
res = res + other
i = i + val_1
end
res
end
def length
@num.length
end
def to_s
@num
end
end
class PrintResult
def print_line(value, space_value)
puts value.to_s.rjust(space_value + 1)
end
def print_result(space_value, *args)
args.each do |value|
print_line(value, space_value)
end
end
end
puts BigInteger.new("11") * BigInteger.new("1111111111111111111111111111111111")