版权声明:Nicolas https://blog.csdn.net/qq_42835910/article/details/87876311
输入整数n(1≤n<231),求至少两个正整数,使得它们的最小公倍数为n,且这些整数的和最小。输出最小的和。
【分析】
本题再次用到了唯一分解定理。设唯一分解式n=a1^p1*a2^p2…,不难发现每个ai^pi作为一个单独的整数时最优。如果就这样匆匆编写程序,可能会掉入陷阱。本题有好几个特殊情况要处理:n=1时答案为1+1=2;n只有一种因子时需要加个1,还要注意n=231-1时不要溢出。
#include <iostream>
#include <cmath>
using namespace std;
const int N = 40000;
int divede(int &n,int d){
int x = 1;
while( n%d == 0){
n /= d;
x *= d;
}
return x;
}
long long solve(int n){
if(n == 1) return 2;
long long ans = 0;
int primeFactor = 0;// 素因子个数
for(int i = 2, m = sqrt(n+0.5); i <= m; i++){
if(n%i == 0){ // 新的素因子
ans += divede(n, i);
primeFactor++;
}
}
if(n > 1) {
primeFactor++;
ans += n;
}
if(primeFactor <= 1) ans++;
return ans;
}
int main(int argc, char** argv) {
int n, cnt = 0;
while(cin>> n && n)
cout<< "Case "<< ++cnt <<": "<< solve(n)<< '\n';
return 0;
}