* Prime factorization is the process of determining which prime numbers multiply to a given number.
* To write optimized code for this concept, we must aware of Mathematical definition clearly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function primeFactors(n) { // Print the number of 2s that divide n while (n % 2 == 0) { console.log(2); n = n / 2; } // n must be odd at this point. So we can skip one element (Note i = i +2) for (var i = 3; i * i <= n; i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { console.log(i); n = n / i; } } // This condition is to handle the case when n is a prime number greater than 2 if (n > 2) { console.log(n); } } |
Time Complexity: O(sqrt(n))
Application Area:
Prime number validation and prime factorization are concepts used in various
computer science applications such as encryption.
Comments
Post a Comment