Program to Find gcd or hcf of two numbers

Problem statement:- Program to Find gcd or HCF of two numbers.

Sample Input/Output:-

Sample Input First:55 255                         Sample Output First: 5

Sample Input Second: 350 450                 Sample Output Second50

Data requirement:-

   Input Data:- num1, num2

  Output Data:-num2

Program in C
  
Here is the source code of the C Program to Find gcd or HCF of two numbers.

Code:

#include<stdio.h>
int main()
{
    int num1,num2;
    printf("Enter two number to find G.C.D:");
    scanf("%d %d",&num1,&num2);
    while(num1!=num2)
    {
       if(num1>num2)
          num1=num1-num2;
       else
          num2=num2-num1;
    }
    printf("The GCD is %d",num2);
}

Input/Output:
Enter two number to find G.C.D:
55
255
The GCD is 5

Program in C++
  
Here is the source code of the C++ Program to Find gcd or HCF of two numbers.

Code:

#include<iostream>
using namespace std;
int main()
{
    int num1,num2;
    cout<<"Enter two number to find G.C.D:";
    cin>>num1>>num2;
    while(num1!=num2)
    {
       if(num1>num2)
          num1=num1-num2;
       else
          num2=num2-num1;
    }
    cout<<"The GCD is "<<num2;
}

Input/Output:
Enter two number to find G.C.D:
350
450
The GCD is 50

Program in Java
  
Here is the source code of the Java Program to Find gcd or HCF of two numbers.

Code:

import java.util.*;
public class GcdOfTwo {
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
int num1,num2;
    System.out.println("Enter two number to find G.C.D:");
    num1=cs.nextInt();
    num2=cs.nextInt();
    
    while(num1!=num2)
    {
       if(num1>num2)
          num1=num1-num2;
       else
          num2=num2-num1;
    }
    System.out.println("The GCD is "+num2);
    cs.close();
}
}

Input/Output:
Enter two number to find G.C.D:
44 22
The GCD is 22

Program in Python
  
Here is the source code of the Python Program to Find gcd or HCF of two numbers.

Code:

print("Enter two number to find G.C.D")
num1=int(input())
num2=int(input())
while(num1!=num2):
   if (num1 > num2):
      num1 = num1 - num2
   else:
      num2= num2 - num1
print("G.C.D is",num1)

Input/Output:
Enter two number to find G.C.D
258
362
G.C.D is 2


Post a Comment

0 Comments