# Java Program to Check Mersenne Number

In the previous article, we have discussed Java Program to Check Cube Number

In this article we are going to understand what Mersenne number is and how we can check whether a number is Mersenne or not in Java with examples.

## Program to Check Mersenne Number

Mersenne numbers are numbers which can be represented in the form of 2n-1.

Example :

• 63: 63 =  64-1 :  26 – 1 Mersenne number
• 7:    7  =  8 – 1 :  23 – 1 Mersenne number
• 9:    9  =  23+1 :  Not a Mersenne number

In the above examples the number 63 and 7 are Mersenne numbers as they are one less than exponents of 2. However 9 is not a Mersenne number.

Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.

Approach :

1. Enter/declare a number and store it .
2. We add 1 to the number and then check if it is a exponential form of 2.
3. If a match is found then the number is said to be Mersenne number.

Program:

import java.util.Scanner;

public class MersenneNumber
{
public static void main(String args[])
{
//Taking the number as input from the user using scanner class
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = scan.nextInt();

boolean flag = false;
int temp = num+1,iter=1;
// Loop runs until the equivalent power is found or
// Until the exponent becomes greater than the number itself
while(Math.pow(2,iter)<=temp)
{
// Checks whether there is some equivalent power of 2
if(Math.pow(2,iter)==temp)
{
flag = true;
break;
}
iter++;
}

if(flag)
{
System.out.println(num+" is a Mersenne number");
}
else
{
System.out.println(num+" is Not a Mersenne number");
}
}
}
Output:

Case-1

Enter a number : 63
63 is a Mersenne number

Case-2

Enter a number : 27
27 is Not a Mersenne number

Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.

Related Java Programs: