I have the following code:
import math
print "Hey, lets solve Task 4 :)"
number1 = input ("How many digits do you want to look at? ")
number2 = input ("What would you like the digits to add up to? ")
final = []
if number1 == 1:
cow = range(1,10)
elif number1 == 2:
cow = range(10,100)
elif number1 == 3:
cow = range(001,1000)
elif number1 == 4:
cow = range(1000,10000)
elif number1 == 5:
cow = range(10000,100000)
elif number1 == 6:
cow = range(100000,1000000)
elif number1 == 7:
cow = range(1000000,10000000)
elif number1 == 8:
cow = range(10000000,100000000)
elif number1 == 9:
cow = range(100000000,1000000000)
elif number1 == 10:
cow = range(1000000000,10000000000)
number3 = cow[-1] + 1
number10 = number3
number8 = number3 - 1
if number1 == 1:
test = range(1,number10)
elif number1 == 2:
test = range(00,number10)
elif number1 == 3:
test = range(000,number10)
elif number1 == 4:
test = range(0000,number10)
elif number1 == 5:
test = range(00000,number10)
elif number1 == 6:
test = range(000000,number10)
elif number1 == 7:
test = range(0000000,number10)
elif number1 == 8:
test = range(00000000,number10)
elif number1 == 9:
test = range(000000000,number10)
elif number1 == 10:
test = range(0000000000,number10)
if number1 == 1:
number7 = number8
elif number1 == 2:
number7 = number8 + 1
elif number1 == 3:
number7 = number8 + 1
elif number1 == 4:
number7 = number8 + 1
elif number1 == 5:
number7 = number8 + 1
elif number1 == 6:
number7 = number8 + 1
elif number1 == 7:
number7 = number8 + 1
elif number1 == 8:
number7 = number8 + 1
elif number1 == 9:
number7 = number8 + 1
elif number1 == 10:
number7 = number8 + 1
n = 0
while n < number7:
a = test[n]
a = str(a)
print a
number4 = sum(int(x) for x in a)
if number4 == number2:
final.append(number4)
n = n + 1
print len(final)
Basically, this code works out how many digits of numbers contain integers which add up to certain numbers. When it is run, it asks how many digits you would like (e.g. 4) and what number you would like them to add up to. For example, you could pick 4 and 18 and it would calculate how many numbers from 1000 - 9999 have integers that add up to 18 (e.g. 4545).
The problem is, the last question asks how many 10 digit numbers add up to 39. Using this code, it would take my computer ages because it has to count from 1 all the way up to the largest 10 digit number. When I tried it, it crashed my computer!
Is there a way to speed up the loop?
Thank you!
range(1000000000,10000000000)is generating 9 billion 64 bit integers in memory, which is 72 GB of memory.