Skip to content

Instantly share code, notes, and snippets.

@ShenTengTu
Created December 27, 2017 10:17
Show Gist options
  • Save ShenTengTu/1d314bf2be0ca46d9277ccfe1978dd6b to your computer and use it in GitHub Desktop.
Save ShenTengTu/1d314bf2be0ca46d9277ccfe1978dd6b to your computer and use it in GitHub Desktop.
Prime factorization base on sieve of Eratosthenes.
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]
*/
@ShenTengTu
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment