1

I'm doing the Project Euler problem 78

Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7

Find the least value of n for which p(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()
4
  • Consider using sqlite3? It automatically spills over to disk when the data gets too large for main memory. Commented Mar 18, 2019 at 21:03
  • 1
    Also, sys.getrecursionlimit() tells you the maximum depth of the Python interpreter stack. Commented Mar 18, 2019 at 21:08
  • @B.Shefter, i know. But at 100,000 recursion i shouldn't have a problem to reach 50,000 Commented Mar 18, 2019 at 22:00
  • You don't have enough call-stack space to do this. Use an iterative solution. See this: stackoverflow.com/questions/26873627/… Commented Mar 19, 2019 at 8:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.