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.
/**
* @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:
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…
View Comments
Thanks for the link to my blog. I wanted to highlight recursion in my post, but you're right, the loop is notably faster in javascript. Glad to see that the core code of my algorithm held up.
Thanks again,
DH
thanks for the code Its most helpful for me
I get an "Uncaught ReferenceError: test is not defined" on this page. And thr tryout form's not working. I assume that the Qunit script's missing, and trips it all up.
You're right! Updated the qunit link to the latest version and it works now.