Here, we have a basic program example to find HCF of two numbers using different languages. HCF or Highest Common Factor is the greatest number which divides each of the two or more numbers. This program is created in c language, c++, Java, and Python.
Code to calculate HCF in C language
void main()
{
int i, n1, n2, j, hcf=1;
printf("\n\n HCF of two numbers:\n ");
printf("----------------------\n");
printf("Input 1st number for HCF: ");
scanf("%d", &n1);
printf("Input 2nd number for HCF: ");
scanf("%d", &n2);
j = (n1<n2) ? n1 : n2;
for(i=1; i<=j; i++)
{
if(n1%i==0 && n2%i==0)
{
hcf = i;
}
}
printf("\nHCF of %d and %d is : %d\n\n", n1, n2, hcf);
}
Code to calculate HCF in C++ language
#include <iostream>
using namespace std;
int main()
{
int i, n1, n2, j, hcf=1;
cout<<"\n\n HCF of two numbers:\n ";
cout<<"----------------------\n";
cout<<"Input 1st number for HCF: ";
cin>>n1;
cout<<"Input 2nd number for HCF: ";
cin>>n2;
j = (n1<n2) ? n1 : n2;
for(i=1; i<=j; i++)
{
if(n1%i==0 && n2%i==0)
{
hcf = i;
}
}
cout<<"\nHCF of "<<n1<<" and "<<n2<<" is : "<<hcf;
}
Code to calculate HCF in Python language
hcf=1
print("\n\n HCF of two numbers:\n ");
print("----------------------\n");
n1 = int(input("Input 1st number for HCF: "))
n2 = int(input("Input 2nd number for HCF: "))
if n1 > n2:
smaller = n2
else:
smaller = n1
for i in range(1, smaller+1):
if((n1 % i == 0) and (n2 % i == 0)):
hcf = i
print("\nHCF of ",n1," and ",n2," is: ",hcf)
Code to calculate HCF in Java language
import java.util.*;
public class hcf {
public static void main(String[] args) {
int i, n1, n2, j, hcf=1;
System.out.println("\n\n HCF of two numbers:\n ");
System.out.println("----------------------\n");
Scanner s=new Scanner(System.in);
System.out.println("Input 1st number for HCF: ");
n1= s.nextInt();
System.out.println("Input 2nd number for HCF: ");
n2= s.nextInt();
j = (n1<n2) ? n1 : n2;
for(i=1; i<=j; i++)
{
if(n1%i==0 && n2%i==0)
{
hcf = i;
}
}
System.out.println("\nHCF of "+n1+" and "+n2+" is: "+hcf);
}
}