UVA 10791 Minimum Sum LCM

来源:互联网 发布:上海软件培训班多少钱 编辑:程序博客网 时间:2024/05/23 11:56

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

借这个题学习了一下质因子。

质因子:能够被一个正整数整除的质数为该整数的质因子。

互质:两个正整数没有相同的质因子

还有就是gcd和lcm的关系:g=gcd l=lcm a*b/g=l

从一行数的最小公倍数n出发,将n从2开始分解质因子

即:10=2*5

100=2*2*5*5

……

然后将相同的质因子相乘,结果相加就是答案。

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>using namespace std;const int INF=0x3f3f3f3f;const int N=110;long long f[N];long long count1;void Init(long long n){    long long m;    m=(long long)sqrt(n+0.5);//加0.5的作用是四舍五入    count1=0;    long long i;    for(i=2;i<=m&&n>1;i++)    {        if(!(n%i))        {            long long fac=1;            while(!(n%i)&&n>1)            {                fac*=i;                n/=i;            }            f[count1++]=fac;//处理后的质因子        }    }    if(n>1) f[count1++]=n;}int main(){    long long n;    int count=0;    while(~scanf("%lld",&n))    {        if(n==0)break;        Init(n);//将n分解为质因子        count++;        long long ans;        if(!count1||count1==1)            ans=n+1;        else        {            ans=0;            int i;            for(i=0;i<=count1-1;i++)            {                ans+=f[i];            }        }        printf("Case %d: %lld\n",count,ans);    }    return 0;}

原创粉丝点击