Is it a Mersenne Prime?
05AB1E, 5 bytes
A positive number in the form 2n - 1 in binary only consists of 1's.
Code:
b`¹pP
Explanation:
b` # Push each digit of the binary representation of the number onto the stack
¹p # Check if the input is prime
P # Take the product of all these digits
Uses the CP-1252 encoding. Try it online! or Verify all test cases.
Jelly, 5 bytes
&‘<ÆP
Try it online!
How it works
&‘<ÆP Main link. Argument: x
‘ Yield x+1.
& Take the bitwise AND of x and x+1.
This yields 0 iff x is a Mersenne number, i.e., iff x+1 is a power of 2.
ÆP Yield 1 if x is a prime, 0 if not.
< Compare the results to both sides,
This yields 1 iff x is both a Mersenne number and a prime.
Python, 45 bytes
lambda n:-~n&n<all(n%i for i in range(2,n))<n
Try it online!
How it works
The three terms of the chained comparison
-~n&n<all(n%i for i in range(2,n))<n
do the following:
-~n&n
computes the bitwise AND of n + 1 and n. Since n consists solely of 1 bits if it is a Mersenne number, the bitwise AND will return 0 if (and only if) this is the case.all(n%i for i in range(2,n))
returns True if and only if n mod i is non-zero for all values of i in [2, …, n - 1], i.e., if and only if n has no positive divisors apart from 1 and n.In other words, all returns True if and only if n is a composite number, i.e., n is either 1 or a prime.
n
is self-explanatory.
The chained comparison returns True if and only if the individual comparisons do the same.
Since all returns either True/1 or False/0,
-~n&n<all(n%i for i in range(2,n))
can only return True if-~n&n
yields 0 (i.e., if n is a Mersenne number) and all returns True (i.e., if n either 1 or a prime).The comparison
all(n%i for i in range(2,n))<n
holds whenever n > 1, but since all returns True if n = 1, it does not hold in this case.