题目
http://acm.hust.edu.cn/vjudge/problem/status.action
题解
手玩一下数据,发现既然和最小,明显,如果n>=2个数有共同的质因数x的话,不如把其中n-1个除以x,依然不变,所以,这些正整数一定不具有相同的质因数,所以联想到唯一分解定理。
因为
lcm(a,b)=p1^max{a1,b1}* … * pn^max{an,bn};
多个数也是一样的,所以比如说你有一个x1=3,一个x2=9,那对于3这个质因子来说x1就是没有用的,如果在n中有2个3的话,只需要一个9.
所以当
x1=p1^a1,
x2=p2^a2,
…
xn=an^pn,
(p1* p2 *…*pn!=0)…时和有最小值
就算想出来了这道题也很难一次AC。比如说这几组数据
输入1 输出2
输入2 输出3
输入7 输出8
输入2147483647 (2^31-1) 输出 2147483648 (注意已经爆int了)
其实这道题数据比较弱,要是有一个大质数的话我就会挂掉,因为我第一次的代码是强行枚举所有质因子,直到n,而不是直到sqrt(n),因为我以前压根就不知道可以只枚举到sqrt(n)。
代码
第一次的有bug的代码,这代码遇到比较大的质数会T掉,所以特判了一下2^31-1(居然过了)。
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int Pow(int a,int p)
{
int ret=1;
while(p)
{
if(p & 1) ret*=a;
a*=a;p>>=1;
}
return ret;
}
int kase=0;
inline void solve(int n)
{
printf("Case %d: ",++kase);
if(n==2147483647){
printf("2147483648\n");return ;
}
int ans=0,ok=0;
for(int P=2;n!=1;P++)
{
int cnt=0;
while(!(n%P)) n/=P,cnt++;
if(cnt) ans+=Pow(P,cnt),ok++;
}
if(!ok) ans=2;
if(ok==1) ans++;
printf("%d\n",ans);
return ;
}
int main()
{
int n;
while(scanf("%d",&n)==1&&n) solve(n);
return 0;
}
这是看了刘汝佳的代码之后改的
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int Pow(int a,int p)
{
int ret=1;
while(p)
{
if(p & 1) ret*=a;
a*=a;p>>=1;
}
return ret;
}
int kase=0;
inline void solve(int n)
{
printf("Case %d: ",++kase);
long long ans=0;
int ok=0,L=sqrt(n+0.5);
for(int P=2;n!=1&&P<=L;P++)
{
int cnt=0;
while(!(n%P)) n/=P,cnt++;
if(cnt) ans+=Pow(P,cnt),ok++;
}
if(!ok) ans=1ll+n;//质数
else if(n!=1) ans+=n;//剩余有东西 ,一个>sqrt(n)的质数
else if(ok==1) ans++;//完全方(==p^n)
printf("%lld\n",ans);
return ;
}
int main()
{
int n;
while(scanf("%d",&n)==1&&n) solve(n);
return 0;
}