How to Factor Numbers in JavaScript?

Estimated read time 1 min read

You can write a custom function in JavaScript to factor numbers. Here is an example of how you can write a function that takes an integer as input and returns its prime factors:

function factorize(number) {
  let factors = [];
  for (let i = 2; i <= number; i++) {
    while (number % i === 0) {
      number /= i;
  return factors;

// Output: [2, 2, 3, 5]

In the example, the function uses a loop to divide the input number by its smallest factor repeatedly, until the result is no longer divisible by any more factors. The factors that the input number was divided by are stored in an array, which is returned as the result of the function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply