
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Prime Numbers in a Range using JavaScript
We are required to write a JavaScript function that takes in two numbers, say, a and b and returns the total number of prime numbers between a and b (including a and b, if they are prime).
For example −
If a = 2, and b = 21, the prime numbers between them are 2, 3, 5, 7, 11, 13, 17, 19
And their count is 8. Our function should return 8.
Let’s write the code for this function −
Example
Following is the code −
const isPrime = num => { let count = 2; while(count < (num / 2)+1){ if(num % count !== 0){ count++; continue; }; return false; }; return true; }; const primeBetween = (a, b) => { let count = 0; for(let i = Math.min(a, b); i <= Math.max(a, b); i++){ if(isPrime(i)){ count++; }; }; return count; }; console.log(primeBetween(2, 21));
Output
Following is the output in the console −
8
Advertisements