Q3. Write a code to find GCD of two numbers
GCD :- GCD stands for Greatest Common Divisor, GCD of two numbers is the largest number that can exactly divide both numbers. It is also called as HCF.
For Example :-
Input = 25 and 10
Output = 5 is the GCD.
As we can see that 5 divides both 25 and 10 and we don’t have any larger number that divides both the numbers therefore, the GCD of 25 and 10 is 5.
Algorithm for GCD
START
1. Input 2 Numbers A and B and declare variable GCD which holds the result.
2. Run Loop i from 1 to i <= A and i <=B
Check if A & B are completely divisible by i or not if yes then
Assign GCD = i
Loop End
3. Output GCD
STOP
Code for GCD
#include <stdio.h>
int main()
{
int num1=25, num2=10, i, gcd;
for(i=1; i <= num1 && i <= num2; ++i)
{
// Checks if i is factor of both integers
if(num1%i==0 && num2%i==0)
gcd = i;
}
printf(“GCD of %d and %d is %d”, num1, num2, gcd);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
int num1=25, num2=10,i,gcd;
for(i=1; i <= num1 && i <= num2; ++i)
{
// Checks if i is factor of both integers
if(num1%i==0 && num2%i==0)
gcd = i;
}
cout << “GCD of “<< num1<<” and “<< num2<<” is “<< gcd;
return 0;
}
public class LFC
{
public static void main(String args[])
{
int num1 = 25, num2 = 10;
int gcd;
for (int i = 1; i < num1 && i < num2; i++) {
if (num1 % i == 0 && num2 % i == 0)
gcd = i;
}
System.out.println(“GCD of ” + num1 +” and ” + num2 + ” is ” + gcd);
}
}
def find_gcd(num1, num2):
# choose the smaller number
if num1 > num2:
smaller = num2
else:
smaller = num1
for i in range(1, smaller+1):
if((num1 % i == 0) and (num2 % i == 0)):
gcd = i
return gcd
num1 = 25
num2 = 10
gcd=find_gcd(num1, num2)
print (“G.C.D. of “, num1, ” and “, num2, ” is “, gcd)
function find_gcd($num1, $num2)
{
// Everything divides 0
if ($num1 == 0)
return $num2;
if ($num2 == 0)
return $num1;
// base case
if($num1 == $num2)
return $num1 ;
// a is greater
if($num1 > $num2)
return find_gcd( $num1-$num2 , $num2 ) ;
return find_gcd( $num1 , $num2-$num1 ) ;
}
// Driver code
$num1 = 25;
$num2 = 10;
echo “GCD of $num1 and $num2 is “, find_gcd($num1 , $num2) ;
Output
GCD of 25 and 10 is 5
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number