72. JAVA Program to find LCM of given n numbers.
How does this program work?
- This program is used to find LCM of given n numbers using JAVA.
- LCM (Least Common Multiple) of given numbers is the smallest number which can be divided by given numbers.
Here is the code
//LCM of n numbers
import java.util.Scanner;class LCM
{
public static void main(String s[] )
{
int n;
System.out.println("Enter n values:");
Scanner skill=new Scanner( System.in);
n=skill.nextInt();
int inputArray[]=new int[n];
System.out.println("Enter "+n+" elements");
for ( int i=0;i< n;i++ )
{
inputArray[i]=skill.nextInt();
}
long lcm=lcmCalculation(inputArray[0],inputArray[1]);
for(int i=2;i< n;i++)
{
lcm=lcmCalculation(lcm,inputArray[i]);
}
System.out.println("The Least Common Multiple of "+n+" numbers is : " + lcm);
}
static long lcmCalculation(long n1,long n2)
{
long temp,i=2,res;
if(n1>n2)
res=n1;
else
res=n2;
temp=res;
while(res%n1!=0 || res%n2!=0)
{
res=temp*i;
i++;
}
return res;
}}