最多约数问题(二)

题意:

最多约数问题:正整数x的约数是能整除x的正整数。正整数x 的约数个数记为div(x)。例如,1,2,5,10 都是正整数10 的约数,且div(10)=4。设a 和b 是2 个正整数,a≤b,找出a和b之间约数个数最多的数x及其最多约数个数。

思路:
  1. 以[a,b]区间的数为单位, 暴力依次找出[a,b]每个数的约数个数
  2. 以质因子为单位,搜索每个落在区间[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;
}


  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值