V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Bill1
V2EX  ›  Python

用 python 写的判断质数的程序,输入一个较大的奇数时它告诉我可以被 2 整除,为什么?

  •  
  •   Bill1 · 2017-01-07 20:30:32 +08:00 · 2283 次点击
    这是一个创建于 2673 天前的主题,其中的信息可能已经有所发展或是发生改变。

    程序代码如下:

    print("To determine whether the prime number")
    primenumbertext=input("Enter a number:")
    primenumber=float(primenumbertext)
    testnumber=2
    
    
    while True:
    	if testnumber==primenumber:
    		print(primenumbertext+" is prime number!")
    		input()
    		break
    	elif primenumber%testnumber==0:
    		testnumbertext=str(testnumber)
    		print(primenumbertext+" can be divisible by "+testnumbertext+" !")
    		input()
    		break
    	testnumber=testnumber+1
    
    5 条回复    2017-01-08 19:44:13 +08:00
    Yinz
        1
    Yinz  
       2017-01-07 21:05:25 +08:00
    Python3 的求模运算里面用的是浮点数除法,超大奇数在浮点数除法时可能会丢失精度,导致结果错误。所以你把程序里面的超大整数套一层 Decimal 封装就好了。
    https://www.v2ex.com/t/243078#r_2718109
    tigerstudent
        2
    tigerstudent  
       2017-01-07 23:41:07 +08:00
    md 你自己将输入值转成 float 了
    zonyitoo
        3
    zonyitoo  
       2017-01-08 03:02:56 +08:00
    primenumber=float(primenumbertext)

    闲得蛋疼?
    Kilerd
        4
    Kilerd  
       2017-01-08 08:20:53 +08:00 via iPhone
    质数还能是 float ???

    BTW ,质数判定算法建议用概率算法。(前段时间研究 1 个月的感受。)
    Bill1
        5
    Bill1  
    OP
       2017-01-08 19:44:13 +08:00
    @Kilerd
    @zonyitoo 和 int 效果相同呀
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2312 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:48 · PVG 18:48 · LAX 03:48 · JFK 06:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.