python能够处理的最大整数是多少_在python中处理任意大数

我正在研究项目Euler,以提高我的编程技巧.在重新访问问题3的代码后,我遇到了一个有趣的问题.这是我的代码:

# prime numbers are only divisible by unity and themselves

# (1 is not considered a prime number by convention)

def isprime(n):

'''check if integer n is a prime'''

# make sure n is a positive integer

n = abs(int(n))

# 0 and 1 are not primes

if n < 2:

return False

# 2 is the only even prime number

if n == 2:

return True

# all other even numbers are not primes

if not n & 1:

return False

# range starts with 3 and only needs to go up the squareroot of n

# for all odd numbers

for x in range(3, int(n**0.5)+1, 2):

if n % x == 0:

return False

return True

try:

num = int(input('Please input a natural number:'))

except ValueError:

print("Erm.. No. I need a number.")

mylist = []

check = True

newnum = num

i= 0

if isprime(num):

print("%r is a prime number."%num)

else:

while check:

if isprime(i):

if newnum % i ==0:

mylist.append(i)

print("%r is a prime factor of %r"%(i,num))

newnum = newnum/i

i=0

if newnum ==1:

check = False

if i==num:

print("I guess the program broke.")

check = False

i+=1

print ("The largest prime factor for %r is:"%num)

print (max(mylist))

print ("The list of prime factors for %r is:"%num)

print (mylist)

所以我遇到的问题是这个代码将永远运行超过17位的数字(我怀疑任何高于144155188075855872,这是2 ^ 59;它适用于一些18位数而不是其他数字).

我发现如果我输入一个比这更高的数字并用Windows计算器检查答案,答案将非常接近整数,但它将有一个小数部分.

如何更改我的函数以接受并正确计算任意大数? (最好不使用非标准库)

谢谢!

解决方法:

Python整数是任意精度的.我在代码中看到的唯一可能无法以高精度工作的是这个浮点计算:

int(n**0.5)+1

由于浮点数是近似值,因此对于大于64位浮点数可以精确表示的数字(大约在2到50之间),您将得到舍入误差.而是使用整数计算:

for x in itertools.count(3, 2):

if x > n ** 2:

break

if n % x == 0:

return False

标签:python

来源: https://codeday.me/bug/20190529/1176255.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值