poj 2429 GCD & LCM Inverse 【java】+【數學】,poj2429gcd

來源:互聯網
上載者:User

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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.