Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to find factors of a number in JS

Tags:

javascript

I am just starting JS, and understand the concept of finding a factor. However, this snippet of code is what I have so far. I have the str variable that outputs nothing but the first factor which is 2. I am trying to add each (int) to the str as a list of factors. What's the wrong in below code snippet?

function calculate(num) {
    var str = "";
    var int = 2;
    if (num % int == 0) {
        str = str + int;
        int++;
    } else {
        int++;
    }
    alert(str);
}

calculate(232);
like image 759
user3371104 Avatar asked Mar 02 '14 16:03

user3371104


People also ask

How do you find the number of factors of a number?

Finding the Number of FactorsStep 1: Do the prime factorization of the given number, i.e., express it as the product of primes. Step 3: Write the prime factorization in the exponent form. Step 3: Add 1 to each of the exponents. Step 4: Multiply all the resultant numbers.

How do you find the prime factorization of a number in Javascript?

function prime_factors(num) { function is_prime(num) { for (let i = 2; i <= Math. sqrt(num); i++) { if (num % i === 0) return false; } return true; } const result = []; for (let i = 2; i <= num; i++) { while (is_prime(i) && num % i === 0) { if (! result. includes(i)) result.


1 Answers

UPDATED ES6 version:

As @gengns suggested in the comments a simpler way to generate the array would be to use the spread operator and the keys method:

const factors = number => [...Array(number + 1).keys()].filter(i=>number % i === 0);
console.log(factors(36));      //  [1, 2, 3, 4, 6, 9, 12, 18, 36]

ES6 version:

const factors = number => Array
    .from(Array(number + 1), (_, i) => i)
    .filter(i => number % i === 0)

console.log(factors(36));      //  [1, 2, 3, 4, 6, 9, 12, 18, 36]

https://jsfiddle.net/1bkpq17b/

  • Array(number) creates an empty array of [number] places

  • Array.from(arr, (_, i) => i) populates the empty array with values according to position [0,1,2,3,4,5,6,7,8,9]

  • .filter(i => ...) filters the populated [0,1,2,3,4,5] array to the elements which satisfy the condition of number % i === 0 which leaves only the numbers that are the factors of the original number.

Note that you can go just until Math.floor(number/2) for efficiency purposes if you deal with big numbers (or small).

like image 107
Guy Avatar answered Oct 19 '22 11:10

Guy