[英]Optimized way of knowing number is prime or not?
def print_prime_factors(number):
# Start with two, which is the first prime
factor = 2
# Keep going until the factor is larger than the number
while factor <= number:
# Check if factor is a divisor of number
if number % factor == 0:
# If it is, print it and divide the original number
print(factor)
number = number / factor
else:
# If it's not, increment the factor by one
factor += 1
return "Done"
print_prime_factors(100)
# Should print 2,2,5,5
# DO NOT DELETE THIS COMMENT
我正在使用這種方式來檢查數字是否為質數。 還有其他快速方法嗎?
你問: Is there any other fast way?
.
一種方法是大約。 通過消除所有偶數因子( 2
除外),將 function 的運行時間減半:
def print_prime_factors_odd(number):
# Start with two, which is the first prime
factor = 2
addend = 1
# Keep going until the factor is larger than the number
while factor <= number:
# Check if factor is a divisor of number
if number % factor == 0:
# If it is, print it and divide the original number
print(factor)
number = number / factor
else:
# If it's not, increment the factor by the addend
factor += addend
addend = 2 # Once factor becomes 3, then use odd factors after that
print("Done")
標志 = 假
if num == 1: print(num, "is not a prime number") elif num > 1: # 檢查因數 for i in range(2, num): if (num % i) == 0: # if factor找到,設置flag為True flag = True # break out of loop break
# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.