推荐学习书目
› 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 · Jan 7, 2017 · 3366 views
    This topic created in 3549 days ago, the information mentioned may be changed or developed.

    程序代码如下:

    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 replies  •  2017-01-08 19:44:13 +08:00
    Yinz
        1
    Yinz  
       Jan 7, 2017
    Python3 的求模运算里面用的是浮点数除法,超大奇数在浮点数除法时可能会丢失精度,导致结果错误。所以你把程序里面的超大整数套一层 Decimal 封装就好了。
    https://www.v2ex.com/t/243078#r_2718109
    Chichele
        2
    Chichele  
       Jan 7, 2017
    md 你自己将输入值转成 float 了
    zonyitoo
        3
    zonyitoo  
       Jan 8, 2017
    primenumber=float(primenumbertext)

    闲得蛋疼?
    Kilerd
        4
    Kilerd  
       Jan 8, 2017 via iPhone
    质数还能是 float ???

    BTW ,质数判定算法建议用概率算法。(前段时间研究 1 个月的感受。)
    Bill1
        5
    Bill1  
    OP
       Jan 8, 2017
    @Kilerd
    @zonyitoo 和 int 效果相同呀
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2638 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 04:13 · PVG 12:13 · LAX 21:13 · JFK 00:13
    ♥ Do have faith in what you're doing.