11

# Greatest Common Divisor - Javascript Problem

I am stuck explaining a solution to myself and I need help.

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 ((typeof a !== 'number') || (typeof b !== 'number'))

return false;

a = Math.abs(a);

b = Math.abs(b);

while (b) {

let c = b;

b = a % b;

a = c;

}

return a;

};

Explanation:

we declare a function 'gcd'

it has 2 parameters: 'a' and 'b'

we first open an if statement to check if our condition is true

we want to know if typeof a or typeof b is not a number

if our condition is true, meaning if typeof a & typeof b are not a number and a string, boolean or any other data type, then we return false and end the function

if our condition is false, which it is, as both (typeof a and typeof b) are numbers then we want to execute the following codewe want to convert our two parameters 'a' & 'b' to absolute positive values

we do that by using Math.abs(a) and Math.abs(b)

we initialize the variable a & b by the output we get from using the Math.abs method on a & b

we then open a while statement

this while loop will loop through a block of code as long as a specified condition is true

if the specified condition is false then the statement after the while loop will be executed

our condition is to check if b is a truthy or falsy value

if it is true then we want to run the block of codewe create a temporary variable 'c'

we initialize it with the value of 'b'

we then use the modulo / remainder operator by dividing a by b

we store the result in b

Help: I need assistance understanding as I am blank from this point onwards.

Thank you in advance !!

11