问题描述:
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 or12, 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 ( 1N231 - 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
本题利用加法原理和迭代法,若求一个数的MinSum LCM,则对这个数进行乘法划分,p=m*n,分别求m,n的MinSum LCM,然后把这两个数加起来,在动态比较MinSum的大小,取最小值。迭代的边界是,n是素数,此时无法进行迭代,直接返回,但如初始数即使素数,则只能划分成1*n,要对这个值进行特殊输出。
#include<iostream>
#include<fstream>
#include<cmath>
#include<cstdlib>
using namespace std;
ifstream fin("C:\\data31.in");
int N;
int cnt=0;
long long LCM(long long n)
{
long long minsum=n;
long long endpos=sqrt(n)+1;
bool isPrime=true;
for(long long i=2;i<endpos&&i<n;++i)
{
if(n%i==0)
{
isPrime=false;
minsum<?=LCM(i)+LCM(n/i);
}
}
//对输出做特殊处理
if(n!=N)
return minsum;
else
{
if(isPrime)
return n+1;
else
return n+1<minsum?n+1:minsum;
}
}
int main()
{
long long n;
while(cin>>N)
cout<<LCM(N)<<endl;
system("pause");
return 0;
}
当输入的数较小时,可对这个算法进行修改,加入一个判定数组,以减少迭代的次数。此时此算法变为动态规划,算法如下
#include<iostream>
#include<fstream>
#include<cmath>
#include<cstdlib>
using namespace std;
ifstream fin("C:\\data31.in");
int N;
int cnt=0;
//这题不定义判定数组的原因是,本题最大输入数可达2147483648,超出了可定义数组的最大长度
int num[1000];
//这就变成动态规划了
int LCM(int n)
{
int& minsum=num[n];
if(minsum>0)
return minsum;
minsum=n;
int endpos=sqrt(n)+1;
bool isPrime=true;
for(int i=2;i<endpos&&i<n;++i)
{
if(n%i==0)
{
isPrime=false;
minsum<?=LCM(i)+LCM(n/i);
}
}
//对输出做特殊处理
if(n!=N)
return minsum;
else
{
if(isPrime)
{
return n+1;
}
else
return n+1<minsum?n+1:minsum;
}
}
int main()
{
int n;
while(cin>>N)
cout<<LCM(N)<<endl;
system("pause");
return 0;
}
//写完之后看了如下网页
链接1__http://blog.csdn.net/luyuncheng/article/details/8495137
链接2___http://blog.csdn.net/goomaple/article/details/8550381
我还有个思维方式没有转变过来的是:计算机的运算速度超快的。而我在数字稍大的时候就会觉得运算时间可能会超时,就会想去优化代码。