Python-质数检查器-质数的乘积 [英] Python-Prime number checker-product of primes

查看:65
本文介绍了Python-质数检查器-质数的乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码来检查一个数字是否为质数.虽然有更有效的方法可以做到这一点,但我确实注意到,虽然这适用于最大的质数,但它对质数的每个乘积都会中断.因此,虽然它正确地将 13 和 17 识别为素数,但它也将 91 (13 × 7) 识别为素数.任何想法为什么?

I wrote the following code to check for whether a number is prime. While there are more efficient ways to do this, I did notice that while this works for the largest of the primes, it breaks for every product of primes. So, while it correctly identifies 13 and 17 as primes, it also identifies 91 (13 × 7) as prime. Any ideas why?

def checkifprime(numtocheck):
    for x in range(2,numtocheck):
        if(numtocheck % x == 0):
            return False
        return True

answer = checkifprime(91)
print (answer)

推荐答案

return True 缩进太多;它在循环内部并导致函数在第一次迭代时退出,因此您的函数实际上只检查数字是否为奇数.

return True is indented too far; it’s inside the loop and causes the function to exit on the first iteration, so your function really only checks whether a number is odd.

def checkifprime(numtocheck):
    for x in range(2, numtocheck):
        if numtocheck % x == 0:
            return False
    return True

这篇关于Python-质数检查器-质数的乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆