尝试编写一个程序,列出数字加起来等于 Python 中的质数的数字。我将如何修复溢出错误?

Trying to script a program that lists numbers whose digits add up to a prime in Python. How would I be able to fix an overflow error?

def isPrime(num):
    s=0
    for j in range (1, num):
        if(num%j==0):
            s=s+1
            if(s>1):
                break
    return(s)

a = 10**20;
b = 10**400;
for i in xrange(a, b):
        if(isPrime(i)==1 and isPrime(sum(int(x) for x in str(i)))==1):
            print('Sum of all digits of', i, 'is', sum(int(x) for x in str(i)))

我的objective是输出10^20到10^400以内的所有数位相加为质数的数字来回答问题,"How many integers in the range [10^20, 10^400] exist such that the sum of their digits is a prime number?"

在谷歌搜索时,我了解到范围会溢出,而 xrange 会更有效率。使用xrange时,出现错误"OverflowError: Python int too large to convert to C long;"。

怎样才能不出错地输出答案?

有人向 python 2.x 提出了与此类似的问题,似乎:Handling big numbers in code 这可能对较小的数字有所帮助...

总的来说,Quora 上的这个答案非常有用:https://www.quora.com/How-large-can-Python-handle-big-number 就像其他人所说的那样,这取决于您有多少可用内存。

来自 Quora 文章:

The real limit depends on the amount of memory Python has access to. If it had, say, 1GB at its disposal, that would amount to approximately 80000000008000000000 bits. That would, therefore, let you have numbers all the way up to 2800000000028000000000. If somehow we could use the Titan supercomputer’s 600+ TiB of CPU memory specifically for making numbers, we could go all the way up to about 22522252. That's a lot.