poj 2429 GCD & LCM Inverse 【java】+【數學】,poj2429gcd
GCD & LCM Inverse
| Time Limit: 2000MS |
|
Memory Limit: 65536K |
| Total Submissions: 9928 |
|
Accepted: 1843 |
Description
Given two positive integers a and b, we can easily calculate the greatest common divisor (GCD) and the least common multiple (LCM) of a and b. But what about the inverse? That is: given GCD and LCM, finding a and b.
Input
The input contains multiple test cases, each of which contains two positive integers, the GCD and the LCM. You can assume that these two numbers are both less than 2^63.
Output
For each test case, output a and b in ascending order. If there are multiple solutions, output the pair with smallest a + b.
Sample Input
3 60
Sample Output
12 15
題意:給出你最大公約數和最小公倍數,讓你求出原來的兩個數a,b;特別的如果有多組的話,輸出和最小的哪一組。
分析:由GCD和LCM之間的關係可得a*b/GCD= LCM; 沒有特別的方法只好枚舉,但是我們可以得出a*b = LCM/GCD;我們要找的是最後的和最小的,所以從sqrt(b/=a)開始到1枚舉就好了。
註:如果用c/c++會逾時的。最後經學長指導改用java就過了。。。又學了一招。
代碼:
import java.util.Scanner;import java.math.*;public class Main{public static void main(String[] args){Scanner cin = new Scanner(System.in);long a, b, x, y;while(cin.hasNext()){a = cin.nextLong();b = cin.nextLong();x = y = 0;b /= a;for(long i = (long)Math.sqrt(b); i > 0; i --){if(b%i == 0&&gcd(i, b/i) == 1){x = i*a; y = b/i*a; break;}}System.out.println(x+" "+y);}}public static long gcd(long a, long b){if(a<b){long t =a; a = b; b = t;}if(b == 0) return a;else return gcd(b, a%b);}}