测试数字时,有些可以工作,例如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))
我希望得到一个数字的所有因素的清单。
答案 0 :(得分:0)
我更改了您的代码,现在它适用于所有自然数:
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))
答案 1 :(得分:0)
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))
答案 2 :(得分:0)
下面的素数因子计算功能比上面的简单得多。剩下的只是对用户输入的完整性检查。
###########################################################
#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))} ')