

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 - 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
- Related Questions & Answers
- Prime numbers within a range in JavaScript
- Sum of prime numbers between a range - JavaScript
- Counting prime numbers that reduce to 1 within a range using JavaScript
- Finding the k-prime numbers with a specific distance in a range in JavaScript
- Print prime numbers in a given range using C++ STL
- Write a Golang program to find prime numbers in a given range
- Python - Find the number of prime numbers within a given range of numbers
- Armstrong numbers between a range - JavaScript
- Prime numbers upto n - JavaScript
- Program to print prime numbers in a given range using C++ STL
- Checking for co-prime numbers - JavaScript
- How to generate Prime Numbers in JavaScript?
- Sum of all prime numbers in JavaScript
- Finding Armstrong numbers in a given range in JavaScript
- Generating n random numbers between a range - JavaScript
Advertisements