问题
I am writing a program that gives me an overflow error. I realized that the cause of that was due to my input which could do inputs till 2147483646. I figured this using the sys.maxint. Anything beyond that gave me an overflow error. How I can take in inputs for large values? For value, 2147483646 my system hangs. How to deal with such an error. The statement of the problem here is given, A number is called lucky if the sum of its digits, as well as the sum of the squares of its digits is a prime number. How many numbers between A and B are lucky?
I am attaching the sample code here.
class luckynumbers():
#required numbers are only 0-9, their values can be stored in a lookup table
def __init__(self):
self.squarelist=[0,1,4,9,16,25,36,49,64,81]
def isEven(self, n):
if n%2 ==0:
return True
else:
return False
def isPrime(self,n):
return_val=True
if n==2:
return_val= True
if not self.isEven(n):
for i in xrange(2,n/2):
if n%i ==0:
return_val=False
break
else:
return_val= False
return return_val
def sumofDigits(self,n):
return sum(map(int, n))
def generateSquares(self, n):
return map(lambda x: self.squarelist[x], map(int,n))
def satisfy(self,n):
return self.isPrime(self.sumofDigits(n)) and self.isPrime(sum(self.generateSquares(n)))
def main():
luckyno=luckynumbers()
t=int(raw_input().rstrip())
count = []
for i in xrange(t):
counts = 0
a,b = map(int, raw_input().rstrip().split())
if a==1:
a=2
for j in xrange(a,b+1,1):
if luckyno.satisfy(str(j)):
counts+=1
count.append(counts)
for i in count:
print i
if __name__=='__main__':
main()
I am still looking at long integers document in python. But haven't figured a way yet. I have tried to use optimization as far as I can think of. Anything more, I will really grateful.
回答1:
The xrange() function is limited to ints (not longs). The code works as expected if you replace the xrange() call where OverflowError occurs with just a range() call.
来源:https://stackoverflow.com/questions/17384151/long-integer-overflow-error-and-resolution