 # 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: Sample Solution:

HTML Code:

``````<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Find all distinct prime factors of a given integer</title>
<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]


[2,13]
[3,5,7]
```

Flowchart: 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

What is the difficulty level of this exercise?

﻿

## JavaScript: Tips of the Day

Classes/function constructors

```class Person {
constructor() {
this.name = 'Owen';
}
}

Person = class AnotherPerson {
constructor() {
this.name = 'Eddie';
}
};

const member = new Person();
console.log(member.name);
```

We can set classes equal to other classes/function constructors. In this case, we set Person equal to AnotherPerson. The name on this constructor is Eddie, so the name property on the new Person instance member is "Eddie".

Ref: https://bit.ly/3jFRBje