我一直试图编写一个程序,它将采用一个输入的数字,并检查它是否是素数.到目前为止,我所做的代码完全可以正常工作,如果这个数字实际上是素数.如果数字不是素数,那就很奇怪了.我想知道是否有人能告诉我代码的问题.
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
Run Code Online (Sandbox Code Playgroud)
当24被输入时给出的结果是:不是素数不是素数而不是素数
我如何修复每个偶数的每个奇数而不是素数的报告素数的错误
Ste*_*ski 64
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')
Run Code Online (Sandbox Code Playgroud)
Your algorithm is equivalent to:
for a in range(a, num):
if a % num == 0:
print('not prime')
break
else: # loop not exited via break
print('prime')
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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.
With these suggestions:
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
Run Code Online (Sandbox Code Playgroud)
Note that this code does not properly handle 0, 1, and negative numbers.
我们通过使用all生成器表达式替换for循环来使这更简单.
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))
Run Code Online (Sandbox Code Playgroud)
Des*_*tor 21
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up
# the square root of n for all odd numbers
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
Run Code Online (Sandbox Code Playgroud)
取自:
Vin*_*kal 12
def is_prime(n):
return all(n%j for j in xrange(2, int(n**0.5)+1)) and n>1
Run Code Online (Sandbox Code Playgroud)
kin*_*all 10
您的代码的两个主要问题是:
else只有当循环退出而没有中断时,才使用带循环的子句来打印"prime".一些非常显着的低效率:
| 归档时间: |
|
| 查看次数: |
235208 次 |
| 最近记录: |