自定义JavaScript GCD函数返回undefined问题排查求助
非递归GCD函数返回undefined的原因排查
问题描述
需要实现求解两个≥1的正整数最大公约数(GCD)的非递归JavaScript函数,测试时发现函数能在控制台输出正确的公约数,但返回值为undefined,导致测试用例报错(例如输入30和12时,日志输出6但返回undefined,提示expected undefined to equal 6)。递归版欧几里得算法函数运行正常,需排查原函数返回undefined的原因。
原函数代码
function mygcd(x, y) { //your code here let gcd = []; let lowestNum; let bigestNum; //detect the lowest and bigest numbers if (x < y) { lowestNum = x; bigestNum = y; } else if (x > y) { lowestNum = y bigestNum = x; } else { lowestNum = x } //check if the bigest num has a modolo == 0 //else loop the lowest num and push in the array if (bigestNum % lowestNum === 0) { return gcd += lowestNum; } else { let arrNum = [] for (let i = 1; i < lowestNum; i++) { // console.log(i) arrNum.push(i) } //loop the array backwards for (i = arrNum.length - 1; i >= 1; i--) { if (lowestNum % arrNum[i] === 0 && bigestNum % arrNum[i] === 0) { console.log(arrNum[i]) if (gcd !== 0) { return } else { // gcd += arrNum[i] let vals = gcd.push(arrNum[i]) console.log(typeof(vals)) } } } } console.log(gcd) return gcd[0]; } console.log(mygcd(30, 12))
递归版正常代码
function mygcd(x, y) { if (!x) return y if (!y) return x return mygcd(y, x % y) } console.log(mygcd(30, 12)) console.log(mygcd(8, 12))
错误原因分析
核心问题:无值return导致undefined
在else分支的循环中,找到符合条件的公约数时,执行了return(未返回任何值),函数直接返回undefined,这就是测试用例报错的根本原因。相等数值分支变量未初始化
当x等于y时,代码只给lowestNum赋值,bigestNum未定义,后续执行bigestNum % lowestNum会抛出ReferenceError,属于潜在bug。gcd数组处理逻辑混乱
初始化gcd为数组,但在第一个if分支中执行return gcd += lowestNum,会把数组转为字符串(比如空数组加12会变成"12"),返回值类型不符合数字预期。循环变量未声明
第二个for循环中的i没有用let声明,会成为全局变量,可能引发其他逻辑冲突。
修复后的非递归函数
function mygcd(x, y) { let lowestNum = Math.min(x, y); let bigestNum = Math.max(x, y); // 两数相等直接返回 if (lowestNum === bigestNum) { return lowestNum; } // 大数能被小数整除,直接返回小数 if (bigestNum % lowestNum === 0) { return lowestNum; } // 从小数的一半开始倒序查找,减少循环次数 for (let i = Math.floor(lowestNum / 2); i >= 1; i--) { if (lowestNum % i === 0 && bigestNum % i === 0) { return i; } } // 输入都是≥1的正整数,兜底返回1 return 1; } console.log(mygcd(30, 12)); // 输出6 console.log(mygcd(8, 12)); // 输出4 console.log(mygcd(5, 5)); // 输出5
修复说明
- 用
Math.min/Math.max简化大小数判断,避免分支遗漏; - 找到公约数时直接返回数值,不再无值return;
- 优化查找范围,从小数的一半开始倒序查找,减少循环次数;
- 补充输入相等的处理逻辑,消除变量未定义的隐患。
内容的提问来源于stack exchange,提问作者Okere chinedu
相关产品推荐
相关产品推荐

