Python质数检查器

编程入门 行业动态 更新时间:2024-10-24 18:24:48
本文介绍了Python质数检查器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在尝试编写一个程序,该程序将输入一个数字,然后检查它是否是素数.如果数字实际上是素数,我到目前为止编写的代码可以完美运行.如果该数字不是质数,则它的行为很奇怪.我想知道是否有人可以告诉我代码有什么问题.

I have been trying to write a program that will take an inputed number, and check and see if it is a prime number. The code that I have made so far works perfectly if the number is in fact a prime number. If the number is not a prime number it acts strange. I was wondering if anyone could tell me what the issue is with the code.

a=2 num=13 while num > a : if num%a==0 & a!=num: print('not prime') a=a+1 else: print('prime') a=(num)+1

输入24时给出的结果是:不是素数不是素数不是素数素数

the result given when 24 is inputed is: not prime not prime not prime prime

我将如何通过报告每个奇数的质数而不是每个偶数的质数来解决错误

How would i fix the error with the reporting prime on every odd and not prime for every even

推荐答案

一旦你知道一个数字不是质数,你就需要停止迭代.找到质数后添加 break 退出 while 循环.

You need to stop iterating once you know a number isn't prime. Add a break once you find prime to exit the while loop.

只需对代码进行最少的更改即可使其正常工作:

Making only minimal changes to your code to make it work:

a=2 num=13 while num > a : if num%a==0 & a!=num: print('not prime') break i += 1 else: # loop not exited via break print('prime')

你的算法相当于:

for a in range(a, num): if a % num == 0: print('not prime') break else: # loop not exited via break print('prime')

如果你把它扔到一个函数中,你可以省去break和for-else:

If you throw it into a function you can dispense with break and for-else:

def is_prime(n): for i in range(3, n): if n % i == 0: return False return True

即使您要像这样对素数进行暴力破解,您也只需要迭代到 n 的平方根.此外,您可以跳过测试两个之后的偶数.

Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n. Also, you can skip testing the even numbers after two.

有这些建议:

import math def is_prime(n): if n % 2 == 0 and n > 2: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True

请注意,此代码无法正确处理0、1 和负数.

Note that this code does not properly handle 0, 1, and negative numbers.

我们通过使用带有生成器表达式的 all 来替换 for 循环来简化此操作.

We make this simpler by using all with a generator expression to replace the for-loop.

import math def is_prime(n): if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))

更多推荐

Python质数检查器

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

发布评论

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

>www.elefans.com

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