你好,我是一个初学者,我被这道题卡住了,这道题要我只用while循环来解决。这道题要我写一个函数,当给定的数字是质数时返回True,如果给定的数字不是质数,则返回False。
到目前为止,我的代码是这样的。
def is_prime(n):
i = 2
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
我的问题是,我认为我的代码对4以上的数字显示正确的输出 而对1、2、3则返回 "无 我已经调试过了,我认为问题出在while循环条件上。但我不知道如何解决这个问题。如果你们中的任何一位专家能帮助我,我将感激不尽。
edit:我修改了while条件,但1还是返回None...而2在应该返回True的时候却返回False。
def is_prime(n):
i = 2
while i <= n:
if n%i != 0:
return True
else:
return False
i+=1
import math;
def is_prime(n):
i = 2
while i < max(math.sqrt(n),2):
if n%i != 0:
return True
else:
return False
if i == 2:
i+=1
else
i+=2
你可以硬编码这3种情况,以防你不想使用 sqrt
:
def is_prime(n):
i = 2
if n in (1,3):
return True
elif n == 2:
return False
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
for x in range(1, 5):
print(x, '=', is_prime(x))
输出。
(1, '=', True)
(2, '=', False)
(3, '=', True)
(4, '=', False)
要不要来点花哨的? 做一个Eratosthenes的筛子吧。
def is_prime(n):
a = list()
# Assume all are prime
a[0:n+1] = (n+1)*[1]
# Start with removing even numbers
i = 2
while i*i <= n:
print ("I: ", i)
# Set all divisible by i to 0
a[0:n+1:i] = len(a[0:n+1:i])*[0]
# If a[n] is zero, return False
if a[n] == 0:
return False
# Increment i until we have a prime number
while a[i] == 0:
i+=1
if a[n] == 0:
return False
else:
return True
如果你想给你的老师留下深刻的印象 你可以给他看一个快速的概率质数 isprime 用于大于2*50的数字. 我在6核AMD上进行了几周的cpu时间压力测试后,没有发现它有任何错误。
import random
import math
def lars_last_modulus_powers_of_two(hm):
return math.gcd(hm, 1<<hm.bit_length())
def fast_probabilistic_isprime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if lars_last_modulus_powers_of_two(hm+hm) != 2:
return False
if pow(2, hm-1, hm) == 1:
return True
else:
return False
def fast_probabilistic_next_prime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if hm % 2 == 0:
hm = hm + 1
hm += 2
while fast_probabilistic_isprime(hm) == False:
hm += 2
return hm
""" hm here is bitlength, which must be larger than 50.
usage is create_probabilistic_prime(1000)
"""
def create_probabilistic_prime(hm):
if 2**hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
num = random.randint(2**hm,2**(hm+1))
return fast_probabilistic_next_prime(num)