The problem asks the number of solutions to the Diophantine equation of the form 1/x + 1/y = 1/z (where z = n!). Rearranging the given equation clearly tells that the answer is the number of factors of z2.
So the problem boils down to finding the number of factors of n!2 (n factorial squared).
我的算法如下
使用埃拉托斯特尼筛法算法为所有
Iterate over all primes P <= n and find its exponent in n!. I did this using step function formula. Let the exponent be K, then the exponent of P in n!2 will be 2K.
使用步骤 2 使用标准公式计算因子数。
For the worst case input of n = 106, my c code gives answer in 0.056s.
I guess the complexity is no way greater than O(n lg n).
But when I submitted the code on the site, I could pass only 3/15 test cases with the verdict on the rest as time limit exceeded.
我需要一些优化该算法的提示。
到目前为止的代码:
#include <stdio.h>
#include <string.h>
#define ULL unsigned long long int
#define MAXN 1000010
#define MOD 1000007
int isPrime[MAXN];
ULL solve(int N) {
int i, j, f;
ULL res = 1;
memset(isPrime, 1, MAXN * sizeof(int));
isPrime[0] = isPrime[1] = 0;
for (i = 2; i * i <= N; ++i)
if (isPrime[i])
for (j = i * i; j <= N; j += i)
isPrime[j] = 0;
for (i = 2; i <= N; ++i) {
if (isPrime[i]) {
for (j = i, f = 0; j <= N; j *= i)
f += N / j;
f = ((f << 1) + 1) % MOD;
res = (res * f) % MOD;
}
}
return res % MOD;
}
int main() {
int N;
scanf("%d", &N);
printf("%llu\n", solve(N));
return 0;
}
你有一个int此处溢出:
for (j = i, f = 0; j <= N; j *= i)
If 46340 < i < 65536对于许多较大的i,在第二次迭代中j如果溢出回绕,将为负数(这是未定义的行为,所以任何事情都可能发生)。