I'm trying to implement GCD function using recursion, but when i make a return value, it always returns undefined, while if i made a console.log(value) it shows it correctly?
here is the code i'm using:
let a = 6 let b = 4 var gcd = gcdRec(a, b) console.log(gcd) //this executes undefined function gcdRec(a, b) { var gcd = 0 if (a % b === 0) { gcd = b return gcd //if i used console.log(gcd) it prints correctly } else { var temp = bb = a % ba = temp if (b === 0) { gcd = a return gcd } gcdRec(a, b) } }
I also tried to define gce before using it, as let gcd =0
then gcd = gcdRec(a,b)
, but it still the same. any idea why it's doing this?
give return statement in function for each condition
let a = 6 let b = 4 var gcd = gcdRec(a, b) console.log(gcd) //this executes undefined function gcdRec(a, b) { var gcd = 0 if (a % b === 0) { gcd = b return gcd //if i used console.log(gcd) it prints correctly } else { var temp = bb = a % ba = temp if (b === 0) { gcd = a return gcd } return gcdRec(a, b) } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.