质数定义:质数(prime number)又称素数。质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。
- 示例解决方案1
有很多方法可以解决这个问题,下面是一些例子:这是一个不同的功能分解来解决问题。
def get_number(prompt):
'''Returns integer value for input. Prompt is displayed text'''
return int(input(prompt)) def is_prime(number):
'''Returns True for prime numbers, False otherwise'''
# Edge Cases
if number == 1:
prime = False
elif number == 2:
prime = True
# All other primes
else:
prime = True
for check_number in range(2, (number / 2) + 1):
if number % check_number == 0:
prime = False
break
return prime def print_prime(number):
prime = is_prime(number)
if prime:
descriptor = ""
else:
descriptor = "not "
print(number, " is ", descriptor, "prime.", sep="", end="\n\n") # never ending loop while 1 == 1:
print_prime(get_number("Enter a number to check. Ctl-C to exit."))
- 示例解决方案2
import sys
number = input("Please enter a number" + "\n" + ">>>")
number = int(number)
if number > 0:
for x in range (2, number): #this range excludes number and 1, both of which number is divisible by
if number % x != 0: #If number isn't evenly divisible by x, start over with the next one
continue
elif number % x == 0: #If number is evenly divisible by x, it can't be prime
sys.exit("The number is not prime.")
sys.exit("The number is prime.") #number wasn't evenly divisible by any x, so it's prime
elif number == 0:
sys.exit("The number is not prime.") #According to the Google, 0 is not prime
else:#if number is less than 0, the number is not prime (according to the Google).
sys.exit("The number is not prime.")
- 示例解决方案3
我觉得这是最简洁的一种
def prime(n):
factor=[i for i in range(2,n) if n%i ==0]
if len(factor)==0:
print(str(n)+"is prime!")
elif n==2:print(str(n)+" " +"is prime!")
else:print("not prime!")
以上就是解决找质数的三种方法,碰到一个问题要多想如何更加简洁高效的实现功能,而不是实现了就行了,对自己要更高要求,这样才会进步的更快。