w3resource

JavaScript: Find all distinct prime factors of a given integer

JavaScript Basic: Exercise-132 with Solution

Write a JavaScript program to find all distinct prime factors of a given integer

Pictorial Presentation:

JavaScript: Find all distinct prime factors of a given integer.

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Find all distinct prime factors of a given integer</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function prime_factors(num) {
  function is_prime(num) {
    for (let i = 2; i <= Math.sqrt(num); i++)
    {
      if (num % i === 0) return false;
    }
    return true;
  }
  const result = [];
  for (let i = 2; i <= num; i++)
  {
    while (is_prime(i) && num % i === 0) 
    {
      if (!result.includes(i)) result.push(i);
      num /= i;
    }
  }
  return result;
}
console.log(prime_factors(100));
console.log(prime_factors(101));
console.log(prime_factors(103));
console.log(prime_factors(104));
console.log(prime_factors(105));

Sample Output:

[2,5]
[101]
[103]
[2,13]
[3,5,7]

Flowchart:

Flowchart: JavaScript - Find all distinct prime factors of a given integer

ES6 Version:

function prime_factors(num) {
  function is_prime(num) {
    for (let i = 2; i <= Math.sqrt(num); i++)
    {
      if (num % i === 0) return false;
    }
    return true;
  }
  const result = [];
  for (let i = 2; i <= num; i++)
  {
    while (is_prime(i) && num % i === 0) 
    {
      if (!result.includes(i)) result.push(i);
      num /= i;
    }
  }
  return result;
}
console.log(prime_factors(100));
console.log(prime_factors(101));
console.log(prime_factors(103));
console.log(prime_factors(104));
console.log(prime_factors(105));

Live Demo:

See the Pen javascript-basic-exercise-132 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to create an array of prefix sums of the given array.
Next: Write a JavaScript program to check whether it is possible to rearrange characters of a given string in such way that it will become equal to another given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters)

Example:

const isAnagram = (str1, str2) => {
  const normalize = str =>
    str
      .toLowerCase()
      .replace(/[^a-z0-9]/gi, '')
      .split('')
      .sort()
      .join('');
  return normalize(str1) === normalize(str2);
};
console.log(isAnagram('iceman', 'cinema')); // true

Output:

true