Concepts Used:
Mathematics
Difficulty Level:
Easy
Problem Statement (Simplified):
gcdof two given numbers.
gcd(m,n)is the largest number possible which divides both.
Test Case:
Input:
1
15 140
Output:
5
Explanation:
5 divides 15 and 140 both and no number larger than 5 divides them completely. So 5 is our answer.
Solving Approach :
Bruteforce Approach :
1) We can check all numbers from 1 to the
Smaller number, the largest number which divides both numbers is gcd of both numbers.2) This approach is not efficient as it takes O(
Smaller Number) time complexity, we can useLong division methodfor efficient approach.
Efficient Approach :
Long Division Method: We repeatedly store remainder i.e (Larger number%Smaller number) and updateLarger numberbySmaller numberuntilsmaller numbercompletely divides thelarger number. LastSmaller Numberafter all the steps is ourgcd..
Example:
Let two numbers are
25and135, so its visual representation for above efficient approach will be,
As soon as our
reminderbecomes0, ourdividendis ourgcd(a,b).So, 5 is our answer.
Solutions:
#include <stdio.h>
int main()
{
int test;
scanf("%d", &test);
while(test--){
int a, b;
scanf("%d%d",&a,&b);
while(1){
if(b%a==0){
printf("%d\n",a);
break;
}
int temp = a;
a = b%a;
b = temp;
}
}
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
int test;
cin>>test;
while(test--){
int a, b;
cin>>a>>b;
while(true){
if(b%a==0){
cout<<a<<endl;
break;
}
int temp = a;
a = b%a;
b = temp;
}
}
}
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
while(test!=0){
int a = sc.nextInt();
int b = sc.nextInt();
while(true){
if(b%a==0){
System.out.println(a);
break;
}
int temp = a;
a = b%a;
b = temp;
}
test--;
}
}
}
[forminator_quiz id="1150"]
This article tried to discuss Mathematics. Hope this blog helps you understand and solve the problem. To practice more problems on Mathematics you can check out .

