为什么每个数字都是素数?

时间:2017-09-26 18:45:41

标签: python primes

这是我的代码:

from time import sleep

n = 5
k = 2
found_factors = 0

while True:
   kinn = n/k

    if (n == k) and found_factors == 0:
        print("Found prime:", n)
        n += 1
        k = 2
        found_factors = 0
        sleep(0.1)
        continue
    elif (n == k) and found_factors > 0:
        n += 1
        k = 2
        found_factors = 0
        continue


    if isinstance(kinn, int) == True:
        found_factors += 1

    k += 1

该程序旨在从5开始查找素数。但由于某种原因,它输出每个数字作为素数!

为什么会这样?

2 个答案:

答案 0 :(得分:1)

describe 'a spec' do def getId 12345 end shared_examples 'using the id' do |the_id| it 'should do something with the id' do expect(id).to eq(12345) expect(the_id).to eq(12345) end end let(:id) { getId } it 'should retrieve id' do expect(id).to eq(12345) end include_examples 'using the id', getId end 总是返回一个浮点数,即使n/k除以k,所以例如n6/2,这是3.0,并且不是float的实例,但是,还有另一种方法可以使用int%之间的模运算符n检查数字是否为整数得到师的剩余部分:

k

通过在程序中替换它,它输出:

if n % k == 0:
        found_factors += 1

答案 1 :(得分:0)

from time import sleep

n = 5.0 # change one of n/k to float so division will not truncate
k = 2
found_factors = 0

while True:
   kinn = n/k # note: in python 2 dividing ints truncates the remainder

    if (n == k) and found_factors == 0:
        print("Found prime:", n)
        n += 1
        k = 2
        found_factors = 0
        sleep(0.1)
        continue
    elif (n == k) and found_factors > 0:
        n += 1
        k = 2
        found_factors = 0
        continue

    # kinn used to truncate to an int, which is why this statement was always hit.
    # By changing the type of n to float, we test for remainder of n/k instead
    if n % k == 0:
        found_factors += 1

    k += 1