我正在寻找一种高效的算法来解决以下问题。设
不久前我在免费资源中发现了以下代码:http://ideone.com/qvxPj
d(n)
表示正整数n
的正因数个数。给定一些1 <= a <= b <= 10^18
,任务是在区间[a..b]
上找到最大的d
值,并且(可能需要更复杂的算法)找到使d
值最大化的数字。不久前我在免费资源中发现了以下代码:http://ideone.com/qvxPj
unsigned long long n, res;
int p, primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 51, 53, 59, 61, 67, 71};
unsigned long long mul(unsigned long long a, unsigned long long b){
unsigned long long res = 0;
while (b){
if (b & 1LL) res = (res + a);
if (res >= n) return 0;
a = (a << 1LL);
b >>= 1LL;
}
return res;
}
void backtrack(int i, int lim, unsigned long long val, unsigned long long r){
if (r > res) res = r;
if (i == p) return;
int d;
unsigned long long x = val;
for (d = 1; d <= lim; d++){
x = mul(x, primes[i]);
if (x == 0) return;
backtrack(i + 1, d, x, r * (d + 1));
}
}
int main(){
p = sizeof(primes) / sizeof(int);
while (scanf("%llu", &n) != EOF){
res = 0;
backtrack(0, 100, 1, 1);
printf("Maximum number of divisors of any number less than %llu = %llu\n", n, res);
}
return 0;
}
如果有人能够解释它的工作原理,我会非常高兴,因为(对我来说)这个程序运行得非常快。
先感谢任何帮助。
mul
函数之前添加一个空行。 - stgatilovd(12)
会是多少? - Dmitry Grigoryev