如何优化因子的发现因子

时间:2015-08-21 18:41:53

标签: algorithm optimization factorial prime-factoring

我正在解决的问题的一部分需要找到一个因子的数量因子。我试过的伪代码是这样的。

x = 2
ans = 1
while(x < n):    # n is given number
    if(isPrime(x)):
        count = 0
        temp = x
        while(temp < n):
            count += n/temp
            temp *= x
        ans *= (count+1)
    x += 1

但根据约束,n的值可能高达10 ^ 8。我该如何优化呢?

1 个答案:

答案 0 :(得分:0)

这些优化既可用于查找素数因子,也可用于寻找因子的所有因子。

使用筛子,获得素数列表比检查每个数字更容易,看它是否是素数。新的伪代码将是:

ans = 0
foreach(x in primes):
    if(x>n) break    # n is given number
    temp = x
    while(temp < n):
        ans += n/temp
        temp *= x

其次,请注意内部循环计算总和(n / x,n / x ^ 2,n / x ^ 3 ......)这可以重写,尽管节省的费用很少。

ans = 0
foreach(x in primes):
    if(x>n) break    # n is given number
    integer temp = n/x
    while(temp>0):
        ans += temp
        temp /= x
相关问题