Skip to main content
1 of 2

Finding the Greatest Common Factor of a list of Numbers in Javascript

The goal of this code is to take an array of two or more positive integers and return their greatest common factor, or GCF. (This is the biggest number that can be divided into all the numbers in the array without any remainder).

I feel like my code is much too long and complicated. Surely there's a more efficient way to do this. Also, I know it's best practice to avoid global variables, and I used one here.

/* Test whether a number is a factor of another number */
function isFactor(num, fact){
    if(num % fact == 0){
        return true;
    }
    else{
        return false;
    }
}

/* List all the factors of a number */
function listFactors(number){
    factors = [1];
    var i = 2;
    while(i <= number){
        if(isFactor(number, i)){
            factors.unshift(i);
        }
        i++;
    }
    return factors;     
}

var toTest = 1;

/* Find the GCF (greatest common factor) of the numbers in an array */
function GCF(intList){
    var GCF = 1;
    var factorsOfEach = [];
    for(item in intList){
        var num = intList[item];
        var factors = listFactors(num);
        factorsOfEach.push(factors);
    }
    var count = 0;
    factorsOfFirst = factorsOfEach[0];
    var length = factorsOfFirst.length;
    while(count < length){
        var toTest = factorsOfFirst[count];
        var passTest = factorsOfEach.every(arrayContains);
        if(passTest){
            GCF = toTest;
            return GCF;
        }
        else{
            count += 1;
        }
    }
    return GCF
}

/* Check whether an array contains the variable "toTest" */
function arrayContains(array){
    if(array.indexOf(toTest) != -1){
        return true}
    else{
    return false}
}

Here is the project I'm using the code for: https://codepen.io/csinclair/pen/mWZPxm