本文介绍了Python,质数检查器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作一个函数来检查一个数字是否是素数,但它告诉我 9 是素数.
Hi i'm making a function that checks if a number is a prime or not but its telling me that 9 is a prime.
def eprimo(num): if num < 2: return False if num == 2: return True else: for div in range(2,num): if num % div == 0: return False else: return True 推荐答案无论检查是否完成,您都将从 for 循环的第一次迭代返回.除非数字绝对不是素数,否则您不应该从循环内部返回.删除 else,只有在循环结束时才返回 True.
You're going to return from the first iteration of that for loop whether you're done checking or not. You shouldn't return from inside the loop unless the number is definitely not prime. Remove the else and only return True if the loop finishes.
def eprimo(num): if num < 2: return False if num == 2: return True else: for div in range(2,num): if num % div == 0: return False return True优化旁注:你真的不需要检查所有 num 以内的所有候选除数.你只需要检查num的平方根.
Optimization side note: You really don't need to check all the divisor candidates up to num. You only need to check up to the square root of num.
更多推荐
Python,质数检查器
发布评论