l=0
temp=[]
for i in range(10000,100000):
for j in range(11000,12000):
n1=str(i)
n2=str(j)
for k in range(0,5):
a=int(n1[k])
b=int(n2[k])
if a b<=9:
s=(a,b)
temp.append(s)
if len(temp)==5:
l =1
temp.clear()
print(l)
this code is not giving any output, it is meant to count the number of 5digit number such that their sum does not involve any carrying
CodePudding user response:
Your code does print stuff out, but the execution time is very high. Your aim should be on reducing the runtime of your code.
One way of doing this is by realizing that for a five-digit number a_1 a_2 a_3 a_4 a_5
, there are (9 - a_1)
ways to pick the first digit of the other summand, (10 - a_2)
ways to pick the second digit of the other summand, (10 - a_2)
ways to pick the third digit of the other summand, etc. (In this calculation, we use9
rather than 10
for the first digit. This is because we can't use 0
for the first digit, but we can for the others.)
By using this observation, we can use a single for
loop, greatly enhancing the runtime. This should run nearly instantaneously.
total = 0
for i in range(10000, 100000):
summand_count = 1
while i != 0:
if i < 10:
summand_count *= (9 - (i % 10))
else:
summand_count *= (10 - (i % 10))
i //= 10
total = summand_count
print(total)
CodePudding user response:
Actually, you can solve this problem without any loops at all: 36*55^4 == 329422500
Test:
s = 0
for i in range(10, 100):
I = str(i)
for j in range(10, 100):
J = str(j)
for k in range(2):
if int(I[k]) int(J[k]) >= 10:
break
else:
s = 1
print(s)
1980
If you want to count distinct pairs in the sense that (10000, 10001) and (10001, 10000) is the same pair, the result will be (36*55^4-4*5^4)/2 4*5^4 == 164712500
Test:
s = 0
for i in range(10, 100):
I = str(i)
for j in range(i, 100):
J = str(j)
for k in range(2):
if int(I[k]) int(J[k]) >= 10:
break
else:
s = 1
print(s)
1000