大数加法 big number add

问题起源于欧拉项目的问题11。要把1000个50位整数累加起来。字符串搞起。

n = 55
def add(a, b):
	while len(a) < n:
		a = "0" + a
	while len(b) < n:
		b = "0" + b

	sum = []
	for _ in range(0, n):
		sum.append(0)
	
	i = n-1
	while i > 0:
		s = int(a[i]) + int(b[i]) + sum[i]
		if s < 10:
			sum[i] = s
		else:
			sum[i] = s - 10
			sum[i-1] = 1 + sum[i-1]
		i -= 1
	
	result = ''
	for i in range(0, n):
		result += str(sum[i])

	return result

#a = "37107287533902102798797998220837590246510135740250"
#b = "46376937677490009712648124896970078050417018260538"
#print add(a,b)


final = ""
for _ in range(0, n):
	final += "0"

f1 = file('input.txt')
while 1:
	line = f1.readline()
	if len(line) == 0:
		break
	line = line.strip("\r\n")
	final = add(line , final)


print len(final)
print final
print final.strip("0")
print final.strip("0")[0:10]

f1.close()


你可能感兴趣的:(大数加法 big number add)