Python质数检查器 [英] Python Prime number checker

查看:42
本文介绍了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

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

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质数检查器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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