我正在尝试创建一个程序,该程序返回任何给定数的最大素数。该代码适用于相对较小的数字,但是一旦它们开始变大,它将永远需要代码才能运行。
memo = {}
def is_prime(n):
if n not in memo:
memo[n] = True
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
memo[n] = False
return False
return memo[n]
def prime_factors(n):
factors = []
prime_factor = []
for i in range(n, 2, -1):
if n % i == 0:
factors.append(i)
for num in factors:
if is_prime(num):
prime_factor.append(num)
break
print(prime_factor)
prime_factors()
总有办法提高效率,我认为这与我指的是prime_factors函数中的另一个函数导致该效率非常低有关。
答案 0 :(得分:1)
不幸的是,我不太了解您的方法,尤其是为什么您总是从一开始就在is_prime(n)
函数中进行计算,这大大增加了大型输入的复杂性。同样,您的for num in factors:
函数中的prime_factors(n)
部分对我来说意义不大。
但是,您可以尝试以下解决方案:
import time
def get_next_prime(n: int = 0):
if n < 1:
return 2
if 1 <= n < 3:
return n + 1
while True:
n += 1
# Corner cases
if n % 2 == 0 or n % 3 == 0:
continue
i = 5
not_prime = False
# check till sqrt(n) because a larger factor of n must be
# a multiple of smaller factor that has been already checked.
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
not_prime = True
break
i = i + 6
if not_prime:
continue
return n
def prime_factors(dividend):
# dividend : divisor = quotient (remainder)
divisor = get_next_prime()
quotient = -1
factors = []
while quotient != 0:
remainder = dividend % divisor
quotient = dividend // divisor
if remainder == 0:
factors.append(divisor)
dividend = quotient
else:
divisor = get_next_prime(divisor)
return factors
start = time.time()
print(prime_factors(899999999998))
end = time.time()
print(end - start)
查看此演示:https://repl.it/repls/DefiantRecursiveWamp
关于适当的算法,请考虑以下示例:
术语:
dividend : divisor = quotient (remainder)
即7:2 = 3(1)
问题:找出 18
的主要因素divisor
的下一个素数: 2 18 : 2 = 9 (0)
dividend
9 : 2 = 4 (1)
divisor
的下一个素数: 3 ; dividend
保持不变9 : 3 = 3 (0)
dividend
3 : 3 = 1 (0)
dividend
1 : 3 = 0 (0)
quotient
是 0 ->停止!主要因素:{2, 3, 3}
答案 1 :(得分:0)
您可以签出list comprehension,generator,itertools。 和内置的地图,过滤器功能