Created
December 27, 2017 10:17
-
-
Save ShenTengTu/1d314bf2be0ca46d9277ccfe1978dd6b to your computer and use it in GitHub Desktop.
Prime factorization base on sieve of Eratosthenes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function primeFactorizationBaseOnEratosthenes(x) { | |
if (x === 0) | |
return; | |
let seq = Array(x + 1); //index:0~x | |
let sqrt = Math.sqrt(x); | |
seq[1] = 1; | |
//Base on sieve of Eratosthene.Get store smallest prime factor. | |
//if index is prime,the value is empty. | |
for (let i = 2; i <= sqrt; i++) { | |
if (!seq[i]) { | |
for (let j = Math.pow(i, 2); j <= x; j += i) { | |
seq[j] = i; //store smallest prime factor(index is composite). | |
} | |
} | |
} | |
//prime factorization | |
let f = []; | |
while (x != 1) { | |
let a = seq[x] ? seq[x] : x; //if value is empty,assign x. | |
f.push(a); | |
x /= a; | |
} | |
return f; | |
} | |
for (let i = 0; i <= 20; i++) { | |
console.log(i, primeFactorizationBaseOnEratosthenes(i)); | |
} | |
/* | |
0 undefined | |
1 [] | |
2 [2] | |
3 [3] | |
4 [2, 2] | |
5 [5] | |
6 [2, 3] | |
7 [7] | |
8 [2, 2, 2] | |
9 [3, 3] | |
10 [2, 5] | |
11 [11] | |
12 [3, 2, 2] | |
13 [13] | |
14 [2, 7] | |
15 [3, 5] | |
16 [2, 2, 2, 2] | |
17 [17] | |
18 [3, 2, 3] | |
19 [19] | |
20 [2, 2, 5] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python implementation: https://gist.github.com/ShenTengTu/bc1cba365e46971c6f62aba8fc803cfa