# 请告诉我为什么它错了（LCM & GCD）

``````class GFG {

// the simple 2 integers recursive to find their GCD.

static int getGcd(int a, int b){
while(a != b){
if(a >b){
a = a-b;
}else{
b= b-a;
}
}
return a;
}

// find GCD in an array that has more than two integers.

static int Gcd(int[] newArray){

int gcd = newArray[0];
for(int i=1; i<newArray.length; i++){
gcd = getGcd(gcd,newArray[i]);
}

return gcd;
}

static int Lcm(int[] newArray){
int multi =1;
for(int i=0; i< newArray.length; i++){
multi = multi* newArray[i];
}
return (multi/gcd);
}

public static void main (String[] args) {
int[] newArray = { 2, 7, 3, 9, 4 };
System.out.println(Gcd(newArray));
System.out.println(Lcm(newArray));
}
}
``````

``````prog.java:33: error: cannot find symbol
return (multi/gcd);
^
symbol:   variable gcd
``````

Lcm() 函数中没有定义 gcd。最后定义的 gcd 是在 Gcd() 函数中，而这不是全局变量 Lcm() 不能使用它。

``````static int Lcm(int[] newArray){
int multi =newArray[0];
int gcd = 0;
for(int i=1; i< newArray.length; i++){
gcd = getGcd(multi, newArray[i]);
if(gcd == 1) {
multi = multi * newArray[i];
}else {
multi = multi * newArray[i] / gcd;
}
}
return multi;
}
``````

0 条评论