Saturday, October 18, 2014

Calculating LCM of N numbers using Euclid's Algorithm

This program calculates the LCM of N numbers using Euclid's method.

Visit here for calculation of LCM using Common Factors Grid Method.

Read about Euclid's method here.

Source: 

public class LCMEuclid {
    
    public static double getGCD(double a, double b){
        double divisor, dividend, remainder = 1; 
         
        if(a>b){dividend = a; divisor = b;}
        else {dividend = b; divisor = a;}
         
        while(true){
            remainder = dividend % divisor;
            dividend = divisor;
            if(remainder==0)break;
            divisor = remainder;
        } 
        return divisor; //GCD - Greatest Common Divisor
    }
    
    public static void main(String[] args){
        double[] array = new double[]{9, 14, 21, 99};
         
        for(int i=0;i<array.length-1;i+=1){
            double GCD = getGCD(array[i], array[i+1]); 
            double product = array[i] * array[i+1];
            double LCM = product/GCD;
            array[i+1] = LCM;
        } 
        System.out.println("LCM is = "+array[array.length-1]);
    }
}
 
Output:
LCM is = 1386.0

1 comment:

  1. How I can get output in integer format????? By using this program

    ReplyDelete