Hello coders, today we are going to solve GCD and LCM CodeChef Solution whose Problem code is FLOW016.
Task
Two integers A and B are the inputs. Write a program to find GCD and LCM of A and B.
Input Format
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer A and B.
Output Format
Display the GCD and LCM of A and B separated by space respectively. The answer for each test case must be displayed in a new line.
Constraints
- 1 ≤ T ≤ 1000
- 1 ≤ A,B ≤ 1000000
Example
Sample Input
3
120 140
10213 312
10 30
Sample Output
20 840
1 3186456
10 30
Solution – GCD and LCM | CodeChef Solution
C++
#include <iostream> #include <algorithm> using namespace std; int main() { // your code goes here int t=0; cin>>t; while(t--) { long long int a=0,b=0; cin>>a>>b; cout<<__gcd(a,b)<<" "<<((a*b)/__gcd(a,b))<<endl; } return 0; }
Python
#Solution Provided by CodingBroz T = int(input()) for i in range(T): num = [int(x) for x in input().split(' ')] a = min(num) b = max(num) multiply = a*b while(b): a,b = b,a%b hcf = a lcm = multiply/hcf print(hcf,int(lcm))
Java
import java.util.*; public class Main { public static void main(String[] args) { Scanner input =new Scanner(System.in); int t=input.nextInt(); long a,b,Gcd,Lcm; while(t-->0) { a=input.nextInt(); b=input.nextInt(); Gcd=getGcd(a,b); Lcm=(a*b)/Gcd; System.out.println(Gcd+" "+Lcm); } } public static long getGcd(long a, long b) { while(a != b) { if(a>b) a=a-b; else b=b-a; } return a; } }
Disclaimer: The above Problem (GCD and LCM) is generated by CodeChef but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.