# Mersenne Number in Java

In this section, we will discuss what is Mersenne number and also create Java programs to check if the given number is a Mersenne number or not. The Mersenne number program frequently asked in Java coding interviews and academics.

## Mersenne Number

In mathematics, a Mersenne number is a number that is in the form of M(n)=2n-1. Where n is an integer. It is an OEIS sequence A000225. If n is prime, the corresponding Mersenne number may be prime and the number called Mersenne prime number. It is an OEIS sequence A000043. It was given the name after the French mathematician Marin Mersenne.

#### Note that most of the Mersenne numbers are prime. The algebraic property of the Mersenne number is useful in determining primality.

The mathematician, Leonhard Euler proved that any even perfect number must have the form 2n-1.

### Mersenne Number Example

If n = 3, 23-1 = 7 (Mersenne)

If n = 8, 28-1 = 255 (Mersenne)

If n = 13, 213-1 = 8191 (Mersenne)

Similarly, we can check the following numbers, also.

0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215, 33554431, 67108863, 134217727, 268435455, 536870911, 1073741823, 2147483647, 4294967295, etc.

### Mersenne Prime

Prime n such that 2n-1 is Prime (OEIS Sequence A000043)

2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657, 37156667, 42643801, 43112609

If n is Prime in 2n-1 (OEIS Sequence A000668)

3, 7, 31, 127, 8191, 131071, 524287, 2147483647, 2305843009213693951, 618970019642690137449562111, 162259276829213363391578010288127, 170141183460469231731687303715884105727

There are some other Mersenne prime that has been calculated.

2521-1

24423-1

219937-1

2261091-1

2261091-1

21398269-1

The largest Mersenne prime (257885161-1) was discovered by the Mathematician Cooper in 2013 that is 17425170 digits long number.

## Steps to Find Mersenne Number

• Read or initialize the value of n.
• Calculate 2 to the power n and store the resultant in a variable res.
• Subtract 1 from the resultant.

The number that we get after subtraction is a Mersenne number.

Let's implement the above steps in a Java program.

## Mersenne Number Java Program

MersenneNumberExample.java

Output 1:

```Enter a number: 127
127 is a Mersenne number.
```

Output 2:

```Enter a number: 88
88 is a not Mersenne number.
```

Let's create a Java program that calculates the Mersenne prime numbers up to 34.

MersennePrimeExample.java

Output 1:

```n	2^n-1

2	3
3	7
5	31
7	127
13	8191
17	131071
19	524287
31	2147483647
```

### Feedback   