Javascript Practice 69: JS Hero - gcd
Question: Write a function gcd that takes two natural numbers and calculates their gcd. Example: gcd (6, 15) should return 3. Answer: function gcd (a,b) { if (b == 0) { return a; } else { let remainder = a % b; return gcd (b, remainder); } } --- we need to understand 'euclid's alogrithm for gcd' --- if we subtract a smaller number from a larger (we reduce a larger number), GCD doesn’t change. So if we keep subtracting repeatedly the larger of two, we end up with GCD. --- now instead of subtraction, if we divide the smaller number, the algorithm stops when we find remainder 0. --- If A = 0 then GCD(A,B)=B, since the GCD(0,B)=B, and we can stop --- If B = 0 then GCD(A,B)=A, since the GCD(A,0)=A, and we can stop. > we declare a function 'gcd' > it has 2 parameters: 'a' and 'b' > if b is equal to 0, then a shall be the gcd (if you understand euclids alogorithm) > if b is not equal to 0, then we calculate the remainder > we create a v...