我必须找到功率最高的素因数。
我已经找到了素数及其功效,但是我不知道如何打印出具有最高功效的素数。
d = 2
p = 0
while(n):
p = 0
while(n%d==0):
p+=1
n=n//d
if(p):
print("{0}^{1}".format(d,p))
d+=1
对于n = 1620,它应该显示3
答案 0 :(得分:0)
您可以构造除数列表,并使用ATL::CComPtr
进行除数:
=ARRAYFORMULA(QUERY(TO_TEXT(Orig!A:Z); "select Col6 where Col4='"&TO_TEXT(C2)&"'"; -1))
它将打印:
from math import sqrt from collections import Counter a = 1620 temp = a divisors = [] # The largest divisor is not more than sqrt(a) for i in range(2, int(sqrt(a)) + 1): # Divide while able while temp % i == 0: temp = temp // i divisors.append(i) # Found all divisors if temp == 1: break # Print the most common divisor print(Counter(divisors).most_common(1)[0])
(3, 4)
是最常见的除数,3
是其计数。因此,如果只需要除数,则可以编写以下行:
4
代替上一个。
答案 1 :(得分:0)
使用代码,保存主要因子并修复无限循环,只需使用max
调用:
d = 2
p = 0
n = 1620
prime_factors = []
while(d < n):
p = 0
while(n % d == 0):
p += 1
n = n // d
if(p):
prime_factors.append((d, p))
d += 1
# Tell max to use the second element (i.e. p) to find the max element
print(max(prime_factors, key=lambda x: x[1])) # (3 , 4)
# or
print("Largest power prime is {0[0]} with a power of {1[1]}".format(max(prime_factors, key=lambda x: x[1])) # Largest power prime is 3 with a power of 4.
可能有比您更快的解决方案(尤其是因为您根本不会短路),但是我认为我会使用您的代码来回答问题,这样您就可以看出我做得更轻松。