Poj 2429 GCD & LCM Inverse [java] + [mathematics], poj2429gcd
GCD & LCM Inverse
Time Limit:2000 MS |
|
Memory Limit:65536 K |
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
Question: give you the maximum common approx. And the least common multiple, and let you find the original two numbers a and B. In particular, if there are multiple groups, the output and the smallest group.
Analysis: a * B/GCD = LCM can be obtained from the relationship between GCD and LCM. There is no special way to enumerate, but we can conclude that a * B = LCM/GCD; we are looking for the final and smallest values, so we can start from sqrt (B/= a) to 1 enumeration.
NOTE: If c/c ++ is used, it will time out. Finally, the senior student guides you to use java instead... I learned another trick.
Code:
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);}}