Let's assume that you want to get the prime factors of a number n
in JavaScript:
javascriptlet getPrimeFactors = (n) => { let factors = { '1': true } for(let i = 2; i <= n; i ++){ while(n % i === 0){ factors[i] = true n = n / i } } return Object.keys(factors) }
For example, let's do it step by step for n = 10
.
terminal# We divide by 2 until the remainder is different from zero # That will prevent that 4, 8, 10 are added as factors i = 2 10 % 2 = 0 factors[2] = true n = 10 / 2 = 5 5 % 2 = 3 # We divide by 3 until the remainder is different from zero # That will prevent that 6, 9 are added as factors i = 3 5 % 3 = 2 i = 4 5 % 4 = 1 i = 5 5 % 5 = 0 factors[5] = true n = 5 / 5 = 1
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.