0

I've wrote a Python program to multiply two numbers recursively. The program is working fine for small digit numbers but when I am increasing the recursive stack to calculate the multiplication of two big numbers having 125 digits each (say) then its not working. The program is crashing and its not printing anything.

class recursionlimit:
    def __init__(self, limit):
        self.limit = limit

    def __enter__(self):
        self.old_limit = sys.getrecursionlimit()
        sys.setrecursionlimit(self.limit)

    def __exit__(self, type, value, tb):
        sys.setrecursionlimit(self.old_limit)


def multiply(x,y):
  
    if x<y:
        return multiply(y,x)

    if y!=0:
        return x + multiply(x,y-1)
    else:
        return 0
        

def random_number():
    number = rt.randint(pow(10,128),pow(10,129))

    return number


def main():
    x = random_number()
    y = random_number()
    
    with recursionlimit(10**9):
        output = multiply(x,y)
      
   
    print(output)
   

main()

Keyvan Soleimani
  • 606
  • 2
  • 4
  • 16
  • Isnt Python Long size 9223372036854775807 or 2^63 - 1. This is 9.223372037×10¹⁸ so I do not think you can use numbers > 18 digits – colin paice Dec 20 '22 at 20:17
  • @colinpaice No, that is incorrect. Python supports arbitrarily large integers, limited only by available memory. See also [Maximum and Minimum values for ints](https://stackoverflow.com/q/7604966/11082165) – Brian61354270 Dec 20 '22 at 20:19
  • 3
    Stepping back for a moment, are you really surprised that you're running out of resources when making on the order of 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 recursive function calls? – Brian61354270 Dec 20 '22 at 20:23
  • Like Brian said, it's an expected behavior. Experiment yourself increasing number of digits like 5, 10, 15, 20, 25, etc. – relent95 Dec 21 '22 at 01:49
  • 1
    If you already know that, then you should be clear on what are you asking for. See [ask]. – relent95 Dec 21 '22 at 01:52

1 Answers1

0

The program will crash as you're making 10^128 recursive calls which attempts to deplete system resources.

By default the maximum recursion limit is 10^3. 10^9 is already large enough to crash most systems. If one recursive call would be a simple 4 bytes, integer, you'd already take 4 GB of memory.

Unluckily for us, a recursive call is considerably larger than 4 bytes.

Bharel
  • 23,672
  • 5
  • 40
  • 80