- 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
Mersenne prime in JavaScript
In Mathematics, a Mersenne prime is a number that can be written in the form M(n) = 2^n − 1 for some integer n and is actually a prime number.
For example − The first four Mersenne primes are 3, 7, 31, and 127
We are required to write a JavaScript function that takes in a number and checks whether it is a Mersenne prime or not. Let’s write the code for this function
Example
const isPrime = num => { let i = 2; while(i <= num / 2){ if(num % i++ === 0){ return false; }; }; return true; } const mersennePrime = num => { if(!isPrime(num)){ return false; }; let i = 0, n = num+1; while(n !== 1){ if(n % 2 !== 0){ return false; }; n /= 2; }; return true; }; console.log(mersennePrime(31)); console.log(mersennePrime(127)); console.log(mersennePrime(3)); console.log(mersennePrime(37)); console.log(mersennePrime(87)); console.log(mersennePrime(7));
Output
The output in the console will be −
true true true false false true
Advertisements