w3resource

JavaScript: All prime factors of a given number

JavaScript Math: Exercise-71 with Solution

Write a JavaScript program to print all the prime factors of a given number.

Visualisation:

C Exercises: Print all prime factors of a given number

Test Data:
(75) -> [3, 5, 5]
(18) -> [2, 3, 3]
(101) -> [101]

Sample Solution:

JavaScript Code:

/**
 * Calculates the prime factors of a given number.
 * @param {number} number - The number to find prime factors for.
 * @returns {array} - An array containing the prime factors of the given number.
 */
const Prime_Factors = (number) => {
  // Initialize an array to store the result factors
  const result_factors = [];
  
  // Loop through numbers starting from 2 up to the square root of the input number
  for (let i = 2; i * i <= number; i++) {
    // Check if 'i' is a factor of 'number'
    while (number % i === 0) {
      // If 'i' is a factor, push it to the result factors array
      result_factors.push(i);
      // Divide 'number' by 'i'
      number = Math.floor(number / i);
    }
  }
  
  // If there is any remainder greater than 1, push it as a prime factor
  if (number > 1) {
    result_factors.push(number);
  }
  
  // Return the array of prime factors
  return result_factors;
};

// Test the function with different numbers
console.log(Prime_Factors(75));  // Output: [ 3, 5, 5 ]
console.log(Prime_Factors(18));  // Output: [ 2, 3, 3 ]
console.log(Prime_Factors(101)); // Output: [ 101 ]

Output:

[3,5,5]
[2,3,3]
[101]

Flowchart:

JavaScript Math flowchart of all prime factors of a given number

Live Demo:

See the Pen javascript-math-exercise-71 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Reverse Polish notation in mathematical expression.
Next: JavaScript Pronic number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.