0

i am trying to find lcm of n numbers and i want my recursion to run upto the last element, but i cant find an efficient method to limit it from going out of bounds at line 41. please suggest any trick.

import java.io.*;
class lcm
{
static int x=1,k=1;
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter the limit");
int n= Integer.parseInt(br.readLine());
System.out.println("enter the numbers");
int L;

int arr[]=new int[n];

for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());

L=lc( arr[0],arr[1],arr,n);
System.out.println(L);
}

static int lc(int min, int max, int arr[], int n)
{
int fact;

if(x<=n-1 )
{
for(int i=1;i<=min;i++)
{
fact=max*i;
if(fact%min==0)
{
k=fact;

break;
}
}
//System.out.println("values of x"+x);
//System.out.println("values of k"+k);
x++;
return lc(arr[x],k,arr,n);
}


else
{
//System.out.println("vale of x"+x);
return k;
}
}
}
  • possible duplicate of [LCM of all the numbers in an array in Java](http://stackoverflow.com/questions/17689529/lcm-of-all-the-numbers-in-an-array-in-java) – Abhishek Aug 27 '14 at 07:38
  • which is this line 41 where the exception occurs? – CodeNewbie Aug 27 '14 at 08:02
  • @Abhishek: not a duplicate. This one has a code, with the user struggling to understand the origin of an ArrayIndexOutOfBoundsException. That question asks for assistance with LCM logic. – CodeNewbie Aug 27 '14 at 08:05
  • line 41:L=lc( arr[0],arr[1],arr,n); yet i found a solution to it. – Jyotsna Gorle Aug 28 '14 at 09:29

1 Answers1

0

i found a solution though i still want to know if the code i wrote is efficient or not?
static int lc(int min, int max, int arr[], int n) { int fact;

if(x<n-1 )
{
for(int i=1;i<=min;i++)
{
fact=max*i;
if(fact%min==0)
{
k=fact;

break;
}
}
System.out.println("values of x"+x);
System.out.println("values of k"+k);
x++;
return lc(arr[x],k,arr,n);
}


else
{
min=arr[x];
max=k;
for(int i=1;i<=min;i++)
{
fact=max*i;
if(fact%min==0)
{
k=fact;

break;
}
}
return k;
}
}
}