Python 转换为字符串或写入文件时对整数值的更改
我的简单素数生成器有点问题 免责声明:我使用的数字非常大——现在超过2000000位,这可能会导致python的不稳定性,但我希望这是一个可以解决的已知问题Python 转换为字符串或写入文件时对整数值的更改,python,large-data,Python,Large Data,我的简单素数生成器有点问题 免责声明:我使用的数字非常大——现在超过2000000位,这可能会导致python的不稳定性,但我希望这是一个可以解决的已知问题 f = open('primes.txt', 'r') #this is a file containing all prime numbers less than n #sequentially. I have another program t
f = open('primes.txt', 'r') #this is a file containing all prime numbers less than n
#sequentially. I have another program that finds and adds
#more prime numbers to this file.
i = 1
for line in f: #Since the primes are separated by line breaks, I take the int of
#each line and multiply them together and stores the massive number
#in a variable called i
i = i*int(line)
f.close()
i = i+1 #since I know that every prime up to a certain point is a factor of
#i, I can add or subtract 1 to guarantee a number that has no prime
#factors (and therefore no factors)
print(i) #prints i to the terminal followed by 3 linebreaks
print("\n\n\n")
h = str(i) #I want to ultimately write i to a text file, but the write command
#doesn't take integer inputs
print(len(h)) #prints how large my new prime is
f = open('largestprime.txt', 'w') #opens a new file and overwrites what's currently inside
if int(h) == i: #I wrote this statement as a check when I started noticing something
#unusual was going on. It basically checks to make sure that the
#string h is the same thing as the integer i before writing to file.
f.write(h)
else:
f.write("Something Hinky's Going On")
input() #Waits for an enter before closing the terminal
这对我来说似乎很简单,但它打印到屏幕上的数字和写入文件的数字每次都不同。下面是最新的例子:
-终端打印:
6690896934...(2,009,810 other digits)...0355781011 (total of 2,009,830 digits)
-而该文件现在包含:
5562116702...(2,007,021 other digits)...6916126637 (total of 2,007,041 digits)
该文件缺少2000多个数字!
我是不是在写文件时出错了?在向文件中写入超长字符串时,python中是否存在已知的错误
任何帮助都将不胜感激。谢谢 最后你能做
f.close()
吗?(如果将适当的与
构造一起使用,则不会出现此问题。)使用long而不是int这是否回答了您的问题?作为旁注。h不一定是素数。它不能被文件中的任何素数整除。它可以被一个更大的素数整除。@pygeek,是的,我们完全同意。我在要求你确认我的理解,从来没有质疑过你说过的任何话。但事实上,OP处理的是如此之大的值,以至于我们在表示足够大的值或不表示足够大的值方面已经超越了任何问题。