- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding the largest prime factor of a number in JavaScript
We are required to write a JavaScript function that takes in a number as the only argument.
The number provided as an argument is guaranteed to be a composite number (the number that has more than two factors). Our function should find the largest prime number that exactly divides the input number.
For example −
If the argument is 72, then the output should be 3.
Because 3 is the largest prime number that exactly divides 72
Example
Following is the code −
const num = 72; const largestPrimeFactor = (num) => { let res = Math.ceil(Math.sqrt(num)); const isPrime = (num) => { let i, limit = Math.ceil(Math.sqrt(num)); for (i = 3; i <= limit; i += 2) { if (num % i === 0) { return false; }; }; return true; }; res = (res & 1) === 0 ? res - 1 : res; while (!(num % res === 0 && isPrime(res))) { res -= 2; }; return res; } console.log(largestPrimeFactor(num));
Output
Following is the output on console −
3
- Related Articles
- Find largest prime factor of a number using C++.
- C Program for Find the largest prime factor of a number?
- Python Program for Find largest prime factor of a number
- C Program for Find largest prime factor of a number?
- Java Program to find largest prime factor of a number
- Prime factor array of a Number in JavaScript
- Finding the nth prime number in JavaScript
- Finding nearest prime to a specified number in JavaScript
- Finding next prime number to a given number using JavaScript
- Finding the largest non-repeating number in an array in JavaScript
- Finding the largest 5 digit number within the input number using JavaScript
- Finding two prime numbers with a specific number gap in JavaScript
- Finding the largest and smallest number in an unsorted array of integers in JavaScript
- k-th prime factor of a given number in java
- JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript

Advertisements