This is a simple JavaScript function that does prime factorization.

I wrote it on an Android phone with online editor (I don't have access to computers in night time):

enter image description here


function factorize(n) {
  if (!(Number.isInteger(n) && n >= 2)) {
    throw 'Input is invalid'
  const factors = []
  while (n % 2 == 0) {
    n /= 2
  for (let i=3; i<=Math.round(Math.sqrt(n)+1); i+=2) {
    while (n % i == 0) {
      n /= i
  if (n > 1) {
  return factors



> Array [2, 2, 2, 3, 3, 3, 3, 3, 3, 7, 773]

The test number is the number of seconds in a Gregorian year.

How can it be improved?

  • \$\begingroup\$ I don't know JavaScript. But how does it handle division /. Is this an integer division or is this a floating point division? If it is floating point, can there occur rounding errors if you have a large n and do a lot of divisions? Usually one uses integer arithmetic for such calculations \$\endgroup\$
    – miracle173
    May 27, 2022 at 9:06

1 Answer 1


Taking a square root is a very slow operation, so it's a bad idea to do it for every iteration of the loop. Rather, you should only update the limit whenever n changes.

  • 2
    \$\begingroup\$ Or use i*i<=n. \$\endgroup\$
    – Teepeemm
    Apr 26, 2022 at 1:40
  • \$\begingroup\$ @Teepeemm But you have still a lot of integer multiplications that are not needed if you calculate the root before the loop. \$\endgroup\$
    – miracle173
    May 27, 2022 at 8:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.