如何比较 Python 中质因数最多的数字?
How to compare numbers for highest number of prime factors in Python?
我必须编写代码才能在输入时获得 10 个数字。然后,找出质因数较多的数。如果两个数具有相同数量的质因数,则打印较大的一个。
例如,对于样本输入:
输入值:
123
43
54
12
76
84
98
678
543
231
输出值应该是这样的:
678 3
这是我的代码,但输出不正确:
import math
# Below function will print the
# all prime factor of given number
def prime_factors(num):
# Using the while loop, we will print the number of two's that divide n
added1 = 0
added2 = 0
while num % 2 == 0:
added1 = 1
print(2, )
num = num / 2
for i in range(3, int(math.sqrt(num)) + 1, 2):
# while i divides n , print i ad divide n
while num % i == 0:
added2 = 1
print(i, )
added2 += 1
num = num / i
if num > 2:
print(num)
added = added1 + added2
print(added)
return added
# calling function
input_numbers = []
for i in range(0,10):
input_numbers.append(int(input()))
contest = 1
for item in input_numbers:
if prime_factors(item) > contest:
contest += 1
contest2 = item
print(contest2)
使用 this answer 中的算法,我写了一个来解决你的问题。
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
input_numbers = []
for i in range(0,10):
input_numbers.append(int(input()))
highest_num = 0
highest_amount = 1
for num in input_numbers:
factors = list(dict.fromkeys(prime_factors(num)))
factors_amount = len(factors)
if factors_amount > highest_amount:
highest_num = num
highest_amount = factors_amount
elif factors_amount == highest_amount:
if num > highest_num:
highest_num = num
print(highest_num,highest_amount)
我必须编写代码才能在输入时获得 10 个数字。然后,找出质因数较多的数。如果两个数具有相同数量的质因数,则打印较大的一个。
例如,对于样本输入: 输入值:
123
43
54
12
76
84
98
678
543
231
输出值应该是这样的:
678 3
这是我的代码,但输出不正确:
import math
# Below function will print the
# all prime factor of given number
def prime_factors(num):
# Using the while loop, we will print the number of two's that divide n
added1 = 0
added2 = 0
while num % 2 == 0:
added1 = 1
print(2, )
num = num / 2
for i in range(3, int(math.sqrt(num)) + 1, 2):
# while i divides n , print i ad divide n
while num % i == 0:
added2 = 1
print(i, )
added2 += 1
num = num / i
if num > 2:
print(num)
added = added1 + added2
print(added)
return added
# calling function
input_numbers = []
for i in range(0,10):
input_numbers.append(int(input()))
contest = 1
for item in input_numbers:
if prime_factors(item) > contest:
contest += 1
contest2 = item
print(contest2)
使用 this answer 中的算法,我写了一个来解决你的问题。
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
input_numbers = []
for i in range(0,10):
input_numbers.append(int(input()))
highest_num = 0
highest_amount = 1
for num in input_numbers:
factors = list(dict.fromkeys(prime_factors(num)))
factors_amount = len(factors)
if factors_amount > highest_amount:
highest_num = num
highest_amount = factors_amount
elif factors_amount == highest_amount:
if num > highest_num:
highest_num = num
print(highest_num,highest_amount)