- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find all prime factors of a number - JavaScript
We are required to write a JavaScript function that takes in a number and returns an array of all the prime numbers that exactly divide the input number.
For example, if the input number is 18.
Then the output should be −
const output = [2, 3];
Example
Let’s write the code for this function −
const num = 18; const isPrime = (n) => { for(let i = 2; i <= n/2; i++){ if(n % i === 0){ return false; } }; return true; }; const findPrimeFactors = num => { const res = num % 2 === 0 ? [2] : []; let start = 3; while(start <= num){ if(num % start === 0){ if(isPrime(start)){ res.push(start); }; }; start++; }; return res; }; console.log(findPrimeFactors(18));
Output
The output in the console: −
[2, 3]
Advertisements