Code of the Day: Javascript, Prime Factors of a Number

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.

  1. Faster performance by eliminating recursion and caching Math.sqrt.
  2. Whole numbers bigger than 1 return an empty array, since they’re not prime numbers.
  3. 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:

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

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

  • 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.

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago