Find GCD of Two Numbers
Ques: Problem: To find GCD of two number.
NOTE:- Please comment down the code in other languages as well below –
C
C++
Java
Python
C
Run
#includeint findGCD(int a, int b) { if (b == 0) return a; return findGCD(b, a % b); } int main() { int num1, num2; printf("Enter the first number: "); scanf("%d", &num1); printf("Enter the second number: "); scanf("%d", &num2); int gcd = findGCD(num1, num2); printf("GCD: %d\n", gcd); return 0; }
C++
Run
#includeusing namespace std; int findGCD(int a, int b) { if (b == 0) return a; return findGCD(b, a % b); } int main() { int num1, num2; cout << "Enter the first number: "; cin >> num1; cout << "Enter the second number: "; cin >> num2; int gcd = findGCD(num1, num2); cout << "GCD: " << gcd << endl; return 0; }
Java
Run
import java.util.Scanner; public class Main { public static int findGCD(int a, int b) { if (b == 0) return a; return findGCD(b, a % b); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); scanner.close(); int gcd = findGCD(num1, num2); System.out.println("GCD: " + gcd); } }
Python
Run
def find_gcd(a, b): while b: a, b = b, a % b return a num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) gcd = find_gcd(num1, num2) print("GCD:", gcd)
int gcd(m,n){
if(n==0)
return m;
if(m==0)
return n;
else
return gdc(n%m,m);
}
Hey there, Kindly join our discord channel for all Technical queries. Our mentors are right there to help you with it.
import math
math.gcd(a,b)
#Python
def gcd_iter(u, v):
while v:
t = u
u = v
v = t % v
return abs(u)
n = 3
m = 6
result = gcd_iter(n, m)
print(result)
#include
int gcd(int a, int b);
int main()
{
int n,m,hcf;
printf(“Enter the two value:”);
scanf(“%d%d”,&n,&m);
hcf=gcd(n,m);
printf(“hcf=%d”,hcf);
return 0;
}
int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
#include
void main()
{
int n1,n2,n3,i,gcd;
printf(“Enter 3 numbers : “);
scanf(“%d %d %d”, &n1, &n2, &n3); for(i=1;i<=n1&&i<=n2&&i<=n3;i++)
{
if(n1%i==0 &&n2%i==0 &&n3%i==0)
{
gcd=i;
}
}
printf("GCD of %d & %d & %d is %d",n1,n2,n3,gcd);
}
In C prog
#include
void main()
{
int n1,n2,n3,i,gcd;
printf(“Enter 3 numbers : “);
scanf(“%d %d %d”, &n1, &n2, &n3);
for(i=1;i<=n1&&i<=n2&&i<=n3;i++)
{
if(n1%i==0 &&n2%i==0 &&n3%i==0)
{
gcd=i;
}
}
printf("GCD of %d & %d & %d is %d",n1,n2,n3,gcd);
}
python
class solution():
def getGCD(self,m,n):
while(n):
t = m
m = n
n = t%n
if m<0:
return -m
else:
return m
m = int(input())
n =int(input())
p = solution()
print(p.getGCD(m,n))
#GCD and LCM of two numbers
m,n=map(int,input().split())
mul=m*n
def gcd(x,y):
if(y==0):
return(x)
else:
return(gcd(y,x%y))
z=gcd(m,n)
lcm=mul/z
print(“GCD is “+str(z))
print(“LCM is “+str(lcm))