【发布时间】:2016-02-09 05:02:14
【问题描述】:
我想找到 [1,107] 范围内的所有数字除数。我知道它可以在 O(sqrt(n)) 中解决。但是在此之前必须运行 Eratosthenes 的筛子,这可以很容易地修改以获得一个数字的素数分解(通过跟踪每个数字的一个素数因子)。所以我想知道使用素数分解生成所有因子会更有效吗?
设 n = p1k1 * p2k2*....*pmkm
我认为这个符号可以在筛后 O(m+Σki) 中得到。
经过一番思考,我想出了以下代码来生成因子:
int factors[]={2,5}; // array containing all the factors
int exponents[]={2,2}; // array containing all the exponents of factors
// exponents[i] = exponent of factors[i]
vector <int> ans; // vector to hold all possible factors
/*
* stores all possible factors in vector 'ans'
* using factors and exponents from index l to r(both inclusive)
*/
void gen(int factors[],int exponents[],vector<int>& ans,int l,int r)
{
if(l==r)
{
int temp = 1;
for(int i=0;i<=exponents[l];i++)
{
ans.push_back(temp);
temp *= factors[l];
}
return;
}
gen(factors,exponents,ans,l+1,r);
int temp=factors[l];
int size = ans.size();
for(int i=1;i<=exponents[l];i++)
{
for(int j=0;j<size;j++)
{
ans.push_back(ans[j]*temp);
}
temp *= factors[l];
}
}
我认为它的时间复杂度至少是 Ω(no of factor) = Ω(∏(1+ki))。
所以我的问题是:
1) 以这种方式生成因子是否比通常更快(O(sqrt(n)) 循环方法)?
2) 上面给出的代码可以优化吗?
【问题讨论】:
标签: c++ c algorithm primes factorization