Poj 2429 GCD & amp; LCM Inverse [java] + [mathematics], poj2429gcd

Source: Internet
Author: User
Tags greatest common divisor

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);}}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.