w3resource

JavaScript: All prime factors of a given number

JavaScript Math: Exercise-71 with Solution

Prime Factors of a Number

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.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that returns an array of prime factors for a given integer using iterative trial division.
  • Write a JavaScript function that recursively factors a number into its prime constituents and returns them in sorted order.
  • Write a JavaScript function that validates input and returns an error if the number is not a positive integer before factoring.
  • Write a JavaScript function that factors a number and also counts the multiplicity of each prime factor in the result.

Go to:


PREV : Reverse Polish Notation (RPN).
NEXT : Check Pronic Number.

Improve this sample solution and post your code through Disqus.

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.