Knowee
Questions
Features
Study Tools

wap in java to find hcf and lcm of 2 numbers

Question

wap in java to find hcf and lcm of 2 numbers

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. The main method prompts the user to enter two numbers.
  2. It then calls the hcf method, passing the two numbers as arguments. This method uses the Euclidean algorithm to find the HCF of the two numbers.
  3. The HCF is then printed to the console.
  4. The main method then calls the lcm method, 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.
  5. The LCM is then printed to the console.

This problem has been solved

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

1/3

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.