While loop validation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

While loop validation

I came across a question that asks to find the GCD (Greatest Common Divisor) of two numbers. I wrote a code for it and it worked fine but I also checked the solution to look more efficient ways to write it. The solution looks like this: function gcd_two_numbers(x, y) { if ((typeof x !== 'number') || (typeof y !== 'number')) return false; x = Math.abs(x); y = Math.abs(y); while(y) { var t = y; y = x % y; x = t; } return x; } console.log(gcd_two_numbers(12, 13)); // outputs 1 I don't understand understand most part of this code but what's most confusing is the while loop. I know it executes it's code when the condition passed to it is true. But in this case the condition passed to it is y (i.e while(y)), where y = 13. How does this validates? And also y doesn't increments or decrements inside the loop so I don't understand how the while loop iterates. Secondly I don't how they could find the gcd with the code in the loop.

13th Oct 2020, 10:08 AM
Logos
Logos - avatar
5 Answers
+ 1
*Tag the language also.. In js, anything other than 0 is evaluated as true.. And empty string, none, undefined, 0, null... are treated as false.. So a number 13 (not 0) is true there.. x=12,y=13 In while loop, t=13 y=12%13=12 x=13 t=12 y=13%12=1 x=12 t=1 y=12%1=0 x=1 While loop y=0 stops.. Output x=1
13th Oct 2020, 10:55 AM
Jayakrishna 🇮🇳
0
Oh great. Thanks for your explanation Jayakrishna🇮🇳 . I understand it now.
13th Oct 2020, 1:27 PM
Logos
Logos - avatar
0
You're welcome..
13th Oct 2020, 1:35 PM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳 can you also explain this code. The same question. This finds the gcd of more than two numbers using an array to input the numbers. I wrote the code, it worked fine but it's nothing like this. function ex9(x, y){ if(!y) return y === 0 ? x : NaN; return ex9(y, x % y); } function gcd(arr){ var n = 0; for( var i = 0; i < arr.length; i++){ n = ex9(arr[i], n); return n; } } console.log(gcd([3,15,27])); console.log(gcd([5,10,15,25]));
13th Oct 2020, 1:36 PM
Logos
Logos - avatar
0
function ex9(x, y){ if(!y) //when y=0 it returns x otherwise it call this same function recursively by x=y, y=x%y return y === 0 ? x : NaN; return ex9(y, x % y); } function gcd(arr){ var n = 0; for( var i = 0; i < arr.length; i++){ n = ex9(arr[i], n); => calling function ( 3,0), (15,3), (27,3) returned value is assigned to N which is new y next return n; } } console.log(gcd([3,15,27])); 3,0 =>0%3=0 n=3 15,3 =>15%3=0 n=3 27,3 => 27%3=0 Return x=3 finally console.log(gcd([5,10,15,25])); 5,0 => 0%5=0 n=5 10,5 =>10%5=0 n=5 15,5 =>15%5=0 n=5 25,5 => 25%5=0 Return x= 5 finally Eddy Ricchy
13th Oct 2020, 1:54 PM
Jayakrishna 🇮🇳