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);
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With