找到n个数字的LCM - 数组越界

时间:2014-08-27 07:35:17

标签: java arrays indexoutofboundsexception

我试图找到lcm的n个数字,我希望我的递归运行到最后一个元素,但我找不到一个有效的方法来限制它超出第41行的界限。 请提出任何技巧。

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;
}
}
}

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,但我仍然想知道我写的代码是否有效?     static int lc(int min,int max,int arr [],int n)     {     事实上;

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;
}
}
}
相关问题