-->

Pages

Monday 6 March 2017

Java Program for calculating HCF and LCM !


Calculating HCF/GCD and LCM are the two most common programming problems that most often than not are asked in various company's interview room or at the time or practical test. So In this article of mine, I am providing the code for both of the programming problems. I have tested and ran these two programs successfully in my system.



Code for LCM:

import java.util.*;
public class LCM {
    
    public static void main(String[] args)
    {
        int num1,num2,i,max,lcm=1;
        System.out.println("Enter the first number");
        Scanner scan=new Scanner(System.in);
        num1=scan.nextInt();
        System.out.println("Enter the second number");
        
        num2=scan.nextInt();
        
        max=(num1>num2)?num1:num2;
        i=max;
        while(true)//it will run the loop forever until the lcm is found
        {
            if(i%num1==0&&i%num2==0)
            {
                lcm=i;
                break;
            }
            i=i+max;
        }
        System.out.println("The LCM of "+num1+" and "+num2+" is : "+lcm);
    }
    
}


Code for HCF or GCD:

import java.util.*;
public class HCF {
    public static void main(String [] args)
    {
        int num1,num2,i,min,hcf=1;
        System.out.println("Enter the first number");
        Scanner scan=new Scanner(System.in);
        num1=scan.nextInt();
        System.out.println("Enter the second number");
        
        num2=scan.nextInt();
        
        min=(num1<num2)?num1:num2;
        for(i=1;i<=min;i++)
        {
            if(num1%i==0&&num2%i==0)
            {
                hcf=i;
            }
        }
        System.out.println("THE HCF OF "+num1+" and "+num2+" is :"+hcf);
    }
    
}

No comments:

Post a Comment

Thanks for Your Time!