[牛客] n的约数 唯一分解定理+dfs

题目链接:n的约数

题意

t次询问,每次给你一个数n,求在[1,n]内约数个数最多的数的约数个数。 (n≤ 1 0 18 {10^{18}} 1018)

题解

我们先来分析这道题,首先我们知道每个数都可以分解成质因数乘积的形式。
n u m = p 1 k 1 ∗ p 2 k 2 ∗ . . . ∗ p m k m {num=p1^{k_1}*p_2^{k_2}*...*p_m^{k_m}} num=p1k1p2k2...pmkm p 1 , p 2 . . . . p m {p_1,p_2....p_m} p1,p2....pm为num的质因数)

那么很容易我们可以得到一个数的约数个数为: ( k 1 + 1 ) ∗ ( k 2 + 1 ) ∗ . . . ∗ ( k m + 1 ) {(k_1+1)*(k_2+1)*...*(k_m+1)} (k1+1)(k2+1)...(km+1)

那么要找1~n里约数最多的,肯定是分解成质因数后个数最多的。
我们打表可以发现前15个质数相乘就达到极限,再多乘一个最小质因数2就会超出 1 0 18 {10^{18}} 1018的范围。可能有人会问为什么只是前15个,后面还有很多数的质因数没在这15个质数里面,注意我们要找的是约数个数最多的,所以质因数个数应该尽可能多,质因数个数要尽可能多,那么质因数应该尽可能小。

我们只需枚举这15个质数,然后再枚举每个质数的个数即可。可以用dfs来求解
我dfs的参数有当前数的大小,当前枚举到第几个质数,当前质数个数的上限,当前数的约数个数。

一开始我没有加上“当前质数个数的上限”参数,结果我超时了。因为一开始为2时的上限是64 ( 2 64 > 1 0 18 {2^{64}}>10^{18} 264>1018),所以我全部设的上限为64,很明显 6 4 15 {64^{15}} 6415必超时。所以必须加上“当前质数个数的上限”参数,很明显为了得到约数个数尽可能多,那么质数越小的时候个数应该尽可能多,所以每搜索到下一个质数的个数一定小于当前质数个数。

代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef long double ld;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define lowbit(x) x&-x

const double PI=acos(-1.0);
const double eps=1e-6;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=1e5+10;
const int maxm=100+10;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

int p[20];
ll n;
void getprime()
{
    
    
	p[0]=0;
	int cnt=1;
	for(int i=2;cnt<=15;i++)
	{
    
    
		bool flag=true;
		for(int j=2;j<=sqrt(i);j++)
			if(i%j==0) {
    
     flag=false; break;}
		if(flag) p[cnt++]=i;
	}
}
ll dfs(ll num,int pos,int lim,ll ans)
{
    
    
	ll tmp=ans;
	if(pos>15) return ans;
	for(int i=1;i<=lim;i++)
	{
    
    
		if(n/p[pos]<num) break;
		num*=p[pos];
		tmp=max(tmp,dfs(num, pos+1,i, ans*(i+1)));
	}
	return tmp;
}
int main()
{
    
    
	getprime();
	int t; scanf("%d",&t);
	while(t--)
	{
    
    
		scanf("%lld",&n);
		printf("%lld\n",dfs(1,1,64,1));
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44235989/article/details/108242301