Click here to Skip to main content
15,884,995 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.

What I have tried:

Answer:

JavaScript
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;
};


My 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 code

>>> we 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 code

>>>> we 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 !!
Posted
Updated 19-Jul-22 4:05am
v2
Comments
Peter_in_2780 30-May-21 22:48pm    
So you have found some code on the internet, and you don't understand it.
One of your problems is that you haven't bothered to search for "Greatest Common Divisor" and read the description of the algorithm.
Then, when you do understand how it works, you could find the bug(s) in the code you grabbed.
Nerav Parekh 31-May-21 1:18am    
Thank you.


You need only find the divisors of one of the values: the smaller.

First, try to divide the larger by the smaller - if it passes you're done.

Next, starting at 1/2 the smaller number (as an int), modulo divide it into the smaller number until you find a factor. Test if this is a factor larger number.
Yes -> you are done.
No -> continue decrementing and testing.
Stop at first "pass" or one, whichever comes first.

 
Share this answer
 
I know this solution is at a too basic level for a lot of you. But being a newbie I did this and thought someone like me might need this. If you have any suggestions about refactoring it, kindly suggest me.

let num1 = +prompt('Enter first number');
let num2 = +prompt('Enter second number');

let num1DivArr = [num1];
let num2DivArr = [num2];

for (let div=0; div <= num1/2; div++) {
    if (num1 % div == 0) {
        num1DivArr.push(div);
    }
}
for (let div=0; div <= num2/2; div++) {
    if (num2 % div == 0) {
        num2DivArr.push(div);
    }
}

const commonDivs = []

for (let i = 0; i <= num1DivArr.length; i++){
    for (let j = 0; j <= num2DivArr.length; j++){
        if (num1DivArr[i] === num2DivArr[j]) {
            commonDivs.push(num1DivArr[i]);
        }
    }
}

let max = commonDivs[0]
for (let el of commonDivs) {
    if (el > max && !isNaN(el)) {
        max = el;
    }
}

console.log(`Greatest Common Divisor for ${num1} and ${num2} is ${max}`)
 
Share this answer
 
Comments
Patrice T 19-Jul-22 10:02am    
Your code is extremely brute force.
Greatest common divisor - Wikipedia[^]
Have a look at "Euclid's algorithm" and "Euclidean algorithm", both are much more efficient.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900