UVA 10791 Minimum Sum LCM

UVA_10791

    通过最小公倍数的求法,我们可以看出最小公倍数取决于每个素因子在各个数中的最高次,因此如果要和最小,我们一定会把同一素因子放在同一整数中。

    再者,由于a*b>a+b,因此我们应该将不同的素因子放在不同的整数中,这样,剩下的工作就是去分解素因子并求和了。

    需要注意几点:①N为1的情况;②N为素数的情况;③N只有一种素因子的情况,如32;④N为2^31-1这个素数时的情况。

#include<stdio.h>
#include<string.h>
#include<math.h>
int N;
void solve()
{
int i, j, k, cnt = 0, temp;
long long int res = 0;
k = (int)sqrt(N + 1);
for(i = 2; i <= k; i ++)
if(N % i == 0)
{
temp = 1;
while(N % i == 0)
{
temp *= i;
N /= i;
}
res += temp;
cnt ++;
}
if(N != 1 || cnt == 0)
{
res += N;
cnt ++;
}
if(cnt == 1)
res ++;
printf("%lld\n", res);
}
int main()
{
int t = 0;
for(;;)
{
scanf("%d", &N);
if(!N)
break;
printf("Case %d: ", ++ t);
solve();
}
return 0;
}


原文地址:https://www.cnblogs.com/staginner/p/2283004.html