Search Tutorials

Tuesday, 23 April 2013

Java code to find HCF & LCM of two numbers using recursion

Java program to find the HCF(Highest Common Factor) & LCM(Least Common Multiple) of two numbers using recursion.

import java.io.*;
class Hcf_Lcm
{
 int n1,n2,hcf,lcm;
 public static void main(String args[]) throws IOException
 {
 Hcf_Lcm call = new Hcf_Lcm();
 call.readData();
 call.display();
 }
 public void readData() throws IOException
 {
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 System.out.print("Enter 1st number : ");
 n1 = Integer.parseInt(br.readLine());
 System.out.print("Enter 2nd number : ");
 n2 = Integer.parseInt(br.readLine());
 }
 public int findHCF(int a, int b)
 {
 if(a==0)
  return b;
 else
  return findHCF(b%a,a);
 }
 public int findLCM(int a, int b, int hcf)
 {
 return (a*b)/hcf;
 }
 public void display()
 {
 hcf = findHCF(n1,n2);
 lcm = findLCM(n1,n2,hcf);
 System.out.println("\nHCF = " +hcf);
 System.out.println("LCM = " +lcm);
 }
}

ALGORITHM:-

1. Start

2. Accept two numbers from user.

3. Using method of recursion, find the HCF.

4. Find the LCM by multiplying the numbers and dividing by their HCF.

5. Print HCF and LCM.

6. End

OUTPUT:-

Java code to find HCF & LCM of two numbers using recursion

Enter 1st number : 8

Enter 2nd number : 36

HCF = 4

LCM = 72

Related Programs:-

Check whether a string is a Palindrome or not

Check the number of Uppercase letters, Lowercase letters, numerals, vowels, spaces & special characters in a string

Read the date, day and year

Read a Date and give the day number

Multiply two Matrices

No comments:

Post a Comment

Back to Top