[英]When finding the prime factors of a number some numbers work but others dont
測試數字時,有些可以工作,例如48,而有些則不能。 我不確定找到數字的所有因素的最佳方法是什么。
def find_primes(n):
factors = []
i = 2
if n == 0:
return 0
if n == 1:
return 1
if n >= 2:
while n % i == 0:
next_n = n / i
factors.append(i)
n = next_n
if n % i != 0:
i += 1
continue
elif i == n:
break
if len(factors) == 0:
return "{} is a prime number.\n".format(initial_n)
else:
return "The prime factors of {} are: {}\n".format(initial_n, factors)
n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))
我期望得到一個數字的所有因素的清單。
我更改了您的代碼,現在它適用於所有自然數:
def find_primes(n):
factors = []
i = 2
if n == 0:
return 0
if n == 1:
return 1
if n >= 2:
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n // i
i += 1
if n > 1:
factors.append(n)
if len(factors) == 1:
return "{} is a prime number.\n".format(initial_n)
else:
return "The prime factors of {} are: {}\n".format(initial_n, factors)
n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))
def find_primes(n):
factors = []
i = 2
if n == 0:
return 0
if n == 1:
return 1
while i <= n:
if n % i == 0:
factors.append(i)
n /= i
else:
i += 1
if len(factors) == 0:
return "{} is a prime number.\n".format(initial_n)
else:
return "The prime factors of {} are: {}\n".format(initial_n, factors)
n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))
下面的主要因子計算功能比上面的簡單得多。 剩下的只是對用戶輸入的完整性檢查。
###########################################################
#Main function to calculate prime factors
def find_prime_factors(n):
factors = []
p = 2
while n > p ** 2:
if n % p == 0:
factors.append(p)
n //= p
else:
p += 1
factors.append(n)
return factors
###########################################################
# Get User input
n = input('Enter a number to find all the Prime Factors: ')
# Check if the entered value is a number
while not n.isnumeric():
print('Entered number was not numeric.')
n = input('Enter a NUMBER to find all the Prime Factors: ')
# Check the entered value is greater than one (1)
# Prime Factor check happens on only positive numbers that are greater than one (1)
while int(n) < 2:
print("Please enter a positive number that is greater than one (1).")
n = input('Enter a NUMBER to find all the Prime Factors: ')
#Python 3.7 string formating
print(f'The prime factor(s) of {n}: {find_prime_factors(int(n))} ')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.