1+ # encoding: utf-8
2+ """
3+ 大数运算的实现
4+ """
5+ __author__ = 'zhanghe'
6+
7+
8+ def add (x , y ):
9+ """
10+ 加法
11+ """
12+ result = [int (p )+ int (q ) for i_p , p in enumerate (('0' * (max (len (x ), len (y ))- len (x ))+ str (x ))[::- 1 ]) for i_q , q in enumerate (('0' * (max (len (x ), len (y ))- len (y ))+ str (y ))[::- 1 ]) if i_p == i_q ]
13+ for index , v in enumerate (result ):
14+ if v >= 10 :
15+ result [index ], k = v % 10 , v / 10
16+ if index + 1 < max (len (str (x )), len (str (y ))):
17+ result [index + 1 ] += k
18+ else :
19+ result .append (k )
20+ return '' .join ([str (i ) for i in result ][::- 1 ])
21+
22+
23+ def multiply (x , y ):
24+ """
25+ 乘法
26+ """
27+ i , result = 0 , '0'
28+ for m in [int (m ) for m in x ][::- 1 ]:
29+ k , t = 0 , []
30+ t .extend ([0 ]* i )
31+ for n in [int (n ) for n in y ][::- 1 ]:
32+ t .append ((int (m )* int (n )+ k ) % 10 )
33+ k = (int (m )* int (n )+ k ) / 10
34+ i += 1
35+ if k > 0 :
36+ t .append (k )
37+ result = add (result , '' .join ([str (item ) for item in t [::- 1 ]]))
38+ return result
39+
40+
41+ def test_add ():
42+ """
43+ 加法测试
44+ """
45+ # 连续进位
46+ a = '8838'
47+ b = '3968'
48+ print add (a , b )
49+ print int (a )+ int (b )
50+
51+ a_1 = '821111111111111181'
52+ b_1 = '94222222222222226200'
53+ print add (a_1 , b_1 )
54+ print int (a_1 )+ int (b_1 )
55+
56+ a_2 = '8211111111111333311181'
57+ b_2 = '94222222222222226200'
58+ print add (a_2 , b_2 )
59+ print int (a_2 )+ int (b_2 )
60+
61+ # 和的长度超过原始数值
62+ a_3 = '82111111111116611181'
63+ b_3 = '94222222222222226200'
64+ print add (a_3 , b_3 )
65+ print int (a_3 )+ int (b_3 )
66+
67+
68+ def test_multiply ():
69+ """
70+ 乘法测试
71+ """
72+ a_1 = '821111111111111181'
73+ b_1 = '94222222222222226200'
74+ print multiply (a_1 , b_1 )
75+ print int (a_1 )* int (b_1 )
76+
77+ a_2 = '8211111111111333311181'
78+ b_2 = '94222222222222226200'
79+ print multiply (a_2 , b_2 )
80+ print int (a_2 )* int (b_2 )
81+
82+ a_3 = '82111111111116611181'
83+ b_3 = '94222222222222226200'
84+ print multiply (a_3 , b_3 )
85+ print int (a_3 )* int (b_3 )
86+
87+ if __name__ == '__main__' :
88+ test_add ()
89+ test_multiply ()
0 commit comments