wap in java to find hcf and lcm of 2 numbers
Question
wap in java to find hcf and lcm of 2 numbers
Solution
Here is a simple Java program to find the HCF (Highest Common Factor) and LCM (Lowest Common Multiple) of two numbers:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number:");
int num1 = scanner.nextInt();
System.out.println("Enter the second number:");
int num2 = scanner.nextInt();
int hcf = hcf(num1, num2);
System.out.println("HCF of " + num1 + " and " + num2 + " is " + hcf);
int lcm = lcm(num1, num2, hcf);
System.out.println("LCM of " + num1 + " and " + num2 + " is " + lcm);
}
public static int hcf(int num1, int num2) {
if (num2 == 0) {
return num1;
}
return hcf(num2, num1 % num2);
}
public static int lcm(int num1, int num2, int hcf) {
return (num1 * num2) / hcf;
}
}
Here's how it works:
- The
mainmethod prompts the user to enter two numbers. - It then calls the
hcfmethod, passing the two numbers as arguments. This method uses the Euclidean algorithm to find the HCF of the two numbers. - The HCF is then printed to the console.
- The
mainmethod then calls thelcmmethod, passing the two numbers and the HCF as arguments. This method calculates the LCM by dividing the product of the two numbers by their HCF. - The LCM is then printed to the console.
Similar Questions
The LCM of two numbers is 360 and their HCF is 15. One of the numbers is 45. The other is Options :406080120
C Program to Find LCM of two
If the LCM and HCF of two numbers are equal, then the numbers must be
HCF and Lcm of two numbers are 7 and 140.If the numbers are between 20 and 45, the numbers are:a.20,49b.35,28c.30,38d.none of these
The LCM of two numbers is 35322. If the numbers are in the ratio 1:3, then HCF is:radio_button_unchecked11774radio_button_unchecked35322radio_button_unchecked23542radio_button_unchecked58870
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.