您的位置:首页 > 其它

Uva 10791 - Minimum Sum LCM 解题报告(因式分解)

2014-03-24 21:40 435 查看


  Minimum Sum LCM 


LCM (Least Common Multiple) of a set of integers is defined as the minimum number, which is a multiple of all integers of that set. It is interesting to note that any positive integer can be expressed as the
LCM of a set of positive integers. For example 12 can be expressed as the
LCM of 1, 12 or 12,
12 or 3, 4 or 4,
6 or 1, 2, 3,
4 etc.

In this problem, you will be given a positive integer N. You have to find out a set of at least two positive integers whose
LCM is N. As infinite such sequences are possible, you have to pick the sequence whose summation of elements is minimum. We will be quite happy if you just print the summation of the elements of this set.
So, for N = 12, you should print 4+3 = 7 as
LCM of 4 and 3 is 12 and
7 is the minimum possible summation.

Input 

The input file contains at most 100 test cases. Each test case consists of a positive integer
N ( 1

N

231
- 1).

Input is terminated by a case where N = 0. This case should not be processed. There can be at most
100 test cases.

Output 

Output of each test case should consist of a line starting with `Case
#: ' where # is the test case number. It should be followed by the summation as specified in the problem statement. Look at the output for sample input for details.

Sample Input 

12
10
5
0


Sample Output 

Case 1: 7
Case 2: 7
Case 3: 6


    解题报告:WA了2次的题。

    首先,推理一下,如果n为素数,那么结果一定是n+1。如果n为一个素数的m次方,那么结果也一定是n+1。可以将n写成p1^e1*p2^2……*pn^en这种形式,那么最小的lcm和一定是p1^e1+p2^2+……+pn^en,因为乘法总是比加法可观,所以都是加法时lcm和最小。第一要注意的是2147483647,普通的int型因式分解将会因为i*i越界而出错,而且此时的结果是2147483648,超过了int型。可以特判,也可以用long long。第二要注意的是1的情况。1的结果是2。代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

typedef long long LL;
int cas=1;
void work(LL n)
{
LL ans=0;
int num=0;
for(LL i=2;i*i<=n;i++) if(n%i==0)
{
num++;
int tmp=1;
while(n%i==0) n/=i,tmp*=i;
ans+=tmp;
}
if(n>1) num++,ans+=n;
if(num==1) ans++;
else if(num==0) ans=2;
printf("Case %d: %lld\n", cas++, ans);
}

int main()
{
int n;
while(~scanf("%d",&n) && n)
work(n);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  因式分解