I was under the impression that python Integers are arbitrary precision. But today while solving a leetCode problem, and multiple submissions with Wrong Answer, I finally added mod
to my solution and it worked. I am confused as to why it happened, following is my code:
import math
class Solution:
def numRollsToTarget(self, d: int, f: int, target: int) -> int:
if target>d*f or target<d:
return 0
memo = {}
return int(self.recurse(d,f,target,memo)%(math.pow(10,9) + 7))
# def recurse(self,d,f,target,memo):
def recurse(self,d,f,target,memo):
key = "%d %d"%(d,target)
if key in memo:
return memo[key]
if d*f<target or target<d:
return 0
elif d==1:
return 1
else:
ways = 0
for i in range(1,f+1):
# following line uncommented, and the next one commented, gives correct answer
#ways = (ways+self.recurse(d-1,f,target-i,memo))%(math.pow(10,9) + 7)
ways += self.recurse(d-1,f,target-i,memo)
memo[key] = ways
return memo[key]
My guess is that overflow is causing the wrong result, modding the partial result everytime while summing solves the problem. Or is there something else I am missing?