Python,质数检查器

编程入门 行业动态 更新时间:2024-10-24 20:19:25
本文介绍了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,质数检查器

本文发布于:2023-11-29 22:52:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:质数   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!