Javascript: Prime Factorization
Today’s code is a enhancement of Code Renaissance‘s version of “Finding Prime Numbers in Javascript”.
Main difference are the following.
- Faster performance by eliminating recursion and caching Math.sqrt.
- Whole numbers bigger than 1 return an empty array, since they’re not prime numbers.
- Decimal values are converted to whole numbers.
/** * @author Larry Battle - http://bateru.com/news/contact-me * @date May 11, 2012 * @license MIT and GPL v3 * @purpose Return the prime factors of a number. * @info - http://bateru.com/news/?s=prime+factors */ var getPrimeFactors = function(num) { num = Math.floor(num); var root, factors = [], x, sqrt = Math.sqrt, doLoop = 1 < num; while( doLoop ){ root = sqrt(num); x = 2; if (num % x) { x = 3; while ((num % x) && ((x += 2) < root)); } x = (x > root) ? num : x; factors.push(x); doLoop = ( x != num ); num /= x; } return factors; } |
Example:
getPrimeFactors(15120) // returns [2, 2, 2, 3, 3, 3, 7]
Demo: