Write a program to input two numbers and find their HCF
Answers
Required Answer:-
Question:
- Write a program to input two numbers and find their HCF.
Solution:
★ HCF of two numbers can be calculated by repeated subtraction. In this approach, we will calculate HCF by repeated subtraction.
Here is the code.
1. Written in Java.
import java.util.*;
public class HCF {
public static void main(String[] args) {
int a, b;
Scanner sc=new Scanner(System.in);
System.out.print("Enter first number: ");
a=sc.nextInt();
System.out.print("Enter second number: ");
b=sc.nextInt();
while(a!=b)
{
if (a>b)
a-=b;
else
b-=a;
}
System.out.println("HCF is: "+a);
sc.close();
}
}
2. Written in Python.
a, b=int(input("Enter first number: ")), int(input("Enter second number: "))
while a!=b:
if a>b:
a=a-b
else:
b=b-a
print("HCF is: ", a)
Output is attached.
Answer:for java
Explanation:
import java.util.*;
public class HCF {
public static void main(String[] args) {
int a, b;
Scanner sc=new Scanner(System.in);
System.out.print("Enter first number: ");
a=sc.nextInt();
System.out.print("Enter second number: ");
b=sc.nextInt();
while(a!=b)
{
if (a>b)
a-=b;
else
b-=a;
}
System.out.println("HCF is: "+a);
sc.close();
}
}