题意:
最多约数问题:正整数x的约数是能整除x的正整数。正整数x 的约数个数记为div(x)。例如,1,2,5,10 都是正整数10 的约数,且div(10)=4。设a 和b 是2 个正整数,a≤b,找出a和b之间约数个数最多的数x及其最多约数个数。
思路:
- 以[a,b]区间的数为单位, 暴力依次找出[a,b]每个数的约数个数
- 以质因子为单位,搜索每个落在区间[a,b]的数的约数个数
第二种的基本思想是一个定理:
设数 x = a1p1 * a2p2 * a3p3 * a4p4 * … * anpn(a1, a2, a3…是质因子),那么x的约数个数为(p1+1) * (p2+1) * (p3+1) * … *(pn+1)。
参看
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const int maxn = 1<<16; //sqrt(4000000000) = 63245, 1<<16 = 65536
LL l, r;
LL max_num, ans; //最大约数的个数及其对应的数
bool a[maxn+10];
int prime[8000], prime_num;
// 初始化素数表
void init_prime(){
for(int i = 0; i <= maxn; ++i) a[i] = 1;
int j;
for(int i = 2; i <= maxn; ++i){
if(!a[i]) continue;
j = i + i;
while(j <= maxn){
a[j] = 0;
j += i;
}
}
j = 0;
for(int i = 2; i <= maxn; ++i){
if(a[i]) prime[j++] = i;
}
prime_num = j;
// printf("num = %d\n", prime_num);
}
//pos: 当前质因子的下标; tot:累积到当前的约数个数; num:累计到当前的数; low,up:当前的区间上下界
void dfs(LL pos, LL tot, LL num, LL low, LL up){
if(num >= l&&(tot > max_num||(tot == max_num&&num < ans))){//一定要保证num >= 区间下界l
max_num = tot;
ans = num;
}
if(low == up&&low > num) dfs(pos, tot*2, num*low, 1, 1); //存在质因子low(=up) > 65536
for(int i = pos; i < prime_num; ++i){
if(prime[i] > up) return;
LL pri = prime[i], num1 = num, tot1 = tot, x = low - 1, x1 = low, y = up;
while(true){
x /= pri;
y /= pri;
x1 /= pri;
if(x == y) break;
tot1 += tot; //质因子指数+1, 约数翻倍
num1 = num1 * pri;
dfs(i+1, tot1, num1, x1, y);
}
//剪枝,算一下当前搜索下去最多有多少约数, 如果不能超过已知的最大值, 尽早中止, 极大提高了效率
LL cnt = log(up) / log(pri);
cnt = (LL)1 << cnt;
if(tot < max_num/cnt) return;
}
}
int main()
{
//freopen("in.txt", "r",stdin);
init_prime();
// for(int i = 0; i < 20; ++i) printf("%d ", prime[i]);
while(scanf("%lld%lld",&l,&r) == 2){
if(1 == l&&1 == r){
max_num = 1;
ans = 1;
}
else{
max_num = 0;
ans = 0;
dfs(0, 1, 1, l, r);
}
printf("max = %lld \t num = %lld\n", max_num, ans);
}
fclose(stdin);
return 0;
}