GCD of Three Numbers in C
C Program to find the GCD of Three Numbers
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers.
C
C++
Java
C
#include <stdio.h>
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
void main()
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
int res=gcd(a,gcd(b,c));
printf("%d",res);
}
C++
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int main()
{
int a,b,c;
cin>>a;
cin>>b;
cin>>c;
cout<<gcd(a,gcd(b,c));
return 0;
}
Java
import java.util.*;
class Main
{
public static int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
System.out.println(gcd(a,gcd(b,c)));
}
}