I'm doing the Project Euler problem 78
Let
p(n)
represent the number of different ways in whichn
coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, sop(5)=7
Find the least value of
n
for whichp(n)
is divisible by one million.
I'm trying to solve this problem using recursion. I know is not the optimal solution neither the fastest one, but I want to make this work if possible. Around n = 6000
it gives me:
MemoryError: Stack overflow
And that is not the only problem. I checked online and the solution is around 53,000. My matrix goes only to 10,000x10,000. If i go to 60,000x60,000 it return a MemoryError. Here is my code:
import sys
from time import process_time as timeit
sys.setrecursionlimit(100000)
table = [10000 * [0] for i in range(10000)]
def partition(sum, largestNumber):
if (largestNumber == 0):
return 0
if (sum == 0):
return 1
if (sum < 0):
return 0
if (table[sum][largestNumber] != 0):
return table[sum][largestNumber]
table[sum][largestNumber] = partition(sum,largestNumber-1) + partition(sum-largestNumber,largestNumber)
return table[sum][largestNumber]
def main():
result = 0
sum = 0
largestNumber = 0
while (result == 0 or result%100000 != 0):
sum += 1
largestNumber += 1
result = int(partition(sum,largestNumber))
if sum%1000 == 0:
print('{} {}'.format(sum,timeit()))
print("n = {}, resultado = {}".format(sum,result))
print('Tempo = {}'.format(timeit()))
if __name__ == '__main__':
main()