码迷,mamicode.com
首页 > 其他好文 > 详细

UVa10791

时间:2016-08-23 23:24:15      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

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
50
Sample Output
Case 1: 7
Case 2: 7
Case 3: 6

题意:

输入整数n(1<=n<2^31),求至少两个正整数,使得它们的最小公倍数为n,且这些整数的和最小。输出最小的和。

分析:

设唯一分解式n=a1^p1 * a2^p2...,不难发现每个a[i]^p[i]作为一个单独的整数时最优。

特例:

n=1时答案为1+1=2。n只有一种因子时需要加个1。另外注意n=2^31-1时不要溢出

技术分享
 1 #include<cmath>
 2 #include<iostream>
 3 using namespace std;
 4 int divide_all(int& n, int d) {
 5   int x = 1;
 6   while(n % d == 0) { n /= d; x *= d; }
 7   return x;
 8 }
 9 long long solve(int n) {
10   if(n == 1) return 2;
11   int m = floor(sqrt(n) + 0.5);
12   long long ans = 0;
13   int pf = 0; // 素因子(prime_factor)个数
14   for(int i = 2; i < m; i++) {
15     if(n % i == 0) { // 新的素因子
16       pf++;
17       ans += divide_all(n, i);
18     }
19   }
20   if(n > 1) { pf++; ans += n; }
21   if(pf <= 1) ans++;
22   return ans;
23 }
24 
25 int main() {
26   int n, kase = 0;
27   while(cin >> n && n)
28     cout << "Case " << ++kase << ": " << solve(n) << "\n";
29   return 0;
30 }
View Code

 

UVa10791

标签:

原文地址:http://www.cnblogs.com/cyb123456/p/5801090.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!