Число - это простое число Мерсенна, если оно простое и может быть записано в виде 2 n -1 , где n - положительное целое число.
Ваша задача состоит в том, чтобы с учетом любого положительного целого числа определить, является ли оно простым числом Мерсенна. Вы можете отправить либо функцию, которая возвращает истинное / ложное значение, либо полную программу, которая выполняет ввод-вывод.
Правила:
- Так как это код-гольф , вы должны стремиться сделать это как можно быстрее. Встроенные разрешены.
- Применяются стандартные лазейки для игры в гольф - вы не можете прочитать простые числа Мерсенна из внешних файлов или жестко закодировать их в своей программе.
- Ваша программа должна работать для значений в пределах стандартного целочисленного размера вашего языка.
Тестовые случаи
Для справки, список (известных) простых чисел Мерсенна можно найти здесь . Некоторые удобные тестовые примеры:
2 -> False
1 -> False
20 -> False
51 -> False
63 -> False
3 -> True
31 -> True
8191 -> True
Всех с Рождеством! Хорошего вам праздника, что бы вы ни отмечали :)
2^n-1
n
is always prime, but knowing that changes nothing, the definition is still correct.Ответы:
Jelly, 5 bytes
Try it online!
How it works
источник
05AB1E, 5 bytes
A positive number in the form 2n - 1 in binary only consists of 1's.
Code:
Explanation:
Uses the CP-1252 encoding. Try it online! or Verify all test cases.
источник
Python, 45 bytes
Try it online!
How it works
The three terms of the chained comparison
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.источник
Brachylog, 7 bytes
Try it online!
A Brachylog program is basically a sequence of constraints which form a chain: the first constraint is between the input and an anonymous unknown (let's call it A for the purpose of this discussion), the second constraint is between that anonymous unknown and a second anonymous unknown (which we'll call B), and so on. As such, the program breaks down like this:
The only way all these constraints can be satisfied simultaneously is if B is a power of 2, i.e. the input is a power of 2 minus 1, and the input is also prime. (Brachylog uses a constraint solver internally, so the program won't be as inefficient as the evaluation order looks; it'll be aware that
C
is of the form[2, Y]
before it tries to expressB
as the exponentiation of two numbers.)Interestingly,
#p+~^
almost works, because Mersenne-like primes can only use 2 as the base in non-degenerate cases (proof), but a) it fails for non-Mersenne primes B-1 as they can be expressed as B¹, and b) the existing Brachylog interpreter seems to be confused (going into an infinite, or at least long-duration, loop) by a program that's that poorly constrained. So 7 bytes seems unlikely to be beaten in Brachylog.источник
Mathematica 26 Bytes
See this proof
Works so long as there are no odd perfect numbers, and none are known to exist.
источник
n(n+1)/2
produces (even) perfect numbers whenevern
is a Mersenne prime (Euclid). It appears to be unknown whether an odd perfect number can have the formn(n+1)/2
, i.e. be a triangular number. All even perfect numbers are triangular where thisn
is a Mersenne prime (Euler).Mathematica,
2926 bytesEdit: Saved 3 bytes thanks to Martin Ender
PrimeQ@#&&IntegerQ@Log2[#+1]&
I suspect this would be faster since the first 42 exponents are hard-coded:
источник
PrimeQ@#&&1>BitAnd[#,#+1]&
Perl 6, 29 bytes
Try it
Expanded:
since Perl 6 has arbitrarily large Ints, it doesn't pad the front of
.base(2)
with0
s.источник
Python,
8382797673 bytesPython 2, 71 bytes
This function implements the Lucas–Lehmer primality test, so while it isn't as short as some of the other Python offerings it's much faster at handling huge inputs.
Here's some test code that runs on Python 2 or Python 3.
output
FWIW, here's a slightly more efficient version of
f
that doesn't re-testm
on every loop:источник
R,
4140 bytesOddly enough the builtin in R
mersenne
takesn
as argument, not2^n-1
.This takes
x
from STDIN, checks if it is prime using thematlab
package and checks if the 2-log ofx+1
is a whole number by taking mod 1 and checking for 'not zero-ness'.Also, if you use the
mersenne
builtin, it ends up being slightly shorter, but feels like cheating:Saved 1 byte thanks to @Billywob
источник
matlab::isprime
to save one byte. Also you have to use<-
for in-function assignment.log2(x+1)
insteadlog(x+1,2)
.Pyke, 10 bytes
Try it here!
источник
Actually, 9 bytes
Try it online!
Explanation:
Since every number of the form 2n-1 has all 1's in its binary representation, a Mersenne prime can be identified as a prime number with that quality.
источник
Jelly, 5 bytes
Alternate approach to @Dennis' existing 5-byte Jelly answer:
Try it online!
How it works:
Since a Mersenne Prime is one less than a power of 2, its binary representation is excusively 1's. The output therefor is 1 for Mersenne primes, and 0 in all other cases .
источник
Ceylon, 66 bytes
Formatted (and commented):
With cheating (hardcoding the results in the range of Ceylon's Integer), we can get a byte shorter (65):
(It looks like the syntax highlighter misunderstands Ceylon's hex numerals as start-of-comment.)
If an anonymous function is okay, this one is 49 bytes:
источник
Wolfram Language (Mathematica), 23 bytes
Try it online!
1 is handled correctly because
PrimeQ[BitAnd[1,1+2]*1] == PrimeQ@1 == False
. Otherwise, forBitAnd[#,#+2]#
to be prime, we need that#
is prime andBitAnd[#,#+2] == 1
, which happens when#
is a Mersenne number.источник
ECMAScript regex,
4231 bytes^(?!(xx+)\1+$)(x(x*)(?=\3$))+x$
Try it online!
Edit: Down to 31 bytes thanks to Neil.
The basic "is a power of 2 minus 1" test is
^(x(x*)(?=\2$))*$
. This works by looping the operation "subtract 1, then divide evenly by 2" until it can be done no further, then asserting that the result is zero. This can be modified to match only numbers ≥1 by changing the last*
to a+
, forcing the loop to iterate at least once. Inserting anx
before the last$
further modifies it to match only numbers ≥3 by asserting that the final result after looping at least once is 1.The related "is a power of 2" test is
^((x+)(?=\2$))*x$
. There is also a shorthand for matching powers of 2 minus 2, discovered by Grimy:^((x+)(?=\2$)x)*$
. All three of these regexes are of the same length.Alternative 31 byte version, by Grimy:
^(?!(xx+)\1+$|((xx)+)(\2x)*$)xx
Try it online!
источник
x(x+)(?=\3$)
be slightly more efficient?Regex (ECMAScript), 29 bytes
Try it online!
Inspired by Grimy in chat
The regex asserts that the input is greater than 3, and that it is neither of the form:
(xx+)\1+
or((xx)+)(\1x)+
.The first matches composite numbers.
The second matches a number that is 1 less than a multiple of some odd number greater than 2.
The first will not match prime numbers, or2n−1 , or numbers that are 1 less than an odd prime.
0
or1
.The second will not match numbers of the form
Since 2 is the only prime that is 1 less than an odd prime, the negative lookahead, together with the assertion that the input is greater than 3, will match only mersenne primes.
источник
Ruby, 47 bytes
источник
Julia, 26 bytes
источник
Python, 65 bytes
Outputs via Exit Code. Recursion Error for False. No error for True.
How it works
Since
2^n-1
in binary is made entirely from 1's, the next2^n-1
number can be generated bynumber|number+1
.This function uses this by recursively going through each
2^n-1
number checking to see if it's a prime number and eqaul to the input. If the number is not a mersenne prime, python will eventually throw an error as the maximum recursion depth would have been exceeded.источник
<0
~>0>
.Pushy, 7 bytes
Try it online!
This takes advantage of the fact that mersenne numbers have only ones in their binary representation:
The stack product will only be
1
if the number has no zeroes in its binary representation, and its primality isTrue
.источник
Pyth, 8 bytes
Verify all the test cases.
Pyth, 8 bytes
Verify all the test cases.
How?
Code Breakdown #1
How does that work?
A number of the form 2n - 1 always contains 1 only when written in binary. Hence, we test if all its binary digits are 1 and if it is prime.
Code Breakdown #2
How does that work?
This tests if the input + 1 is a power of two (i.e. if it is a Mersenne number), and then performs the primality test. In Python,
bool
is a subclass ofint
, so truthy is treated as 1 and falsy is treated as 0. To avoid checking explicitly that one is 0 and the other is 1, we compare their values using<
(since we only have 1 such case).источник
Java 8,
535249 bytesBug-fixed and golfed by 4 bytes thanks to @Nevay.
Explanation:
Try it here.
источник
true
for every prime >2, not only for Mersenne primes, 56 bytes:n->{for(int i=2;i<n;n&=-n%i++>>-1);return(n&n+1)<1&n>2;}
n->{int i=1;for(;++i<n&n%i>0;);return(n&n+1|i^n)<1;}
n->{int i=1;for(;n%++i>0;);return(n&n+1|i^n)==0;}
Python 3, 68 bytes
Try it here
Python 2, 63 bytes
Try it here
Thanks for suggestion Jonathan
Open to any suggestions for reducing the bytecount.
источник
1 and
~>1and
.Japt, 6 bytes
Run it or Run all test cases
источник
©
with bitwise&
for consistent output, if you want.Python, 93 Bytes
This code would work in both Python 2 and Python 3 so I have not specified a version.
источник
Racket 76 bytes
Ungolfed:
Testing:
Output:
источник
PHP, 53 bytes
takes command line argument; prints
1
for Mersenne prime, empty string else. Run with-r
.breakdown
источник
C, 94 bytes
Returns 1 if the number is a Mersenne Prime, 0 otherwise.
источник
~x+g(2,n)
instead ofx^g(2,n)-1
Scala, 59 Bytes
This function requires the input to be a
BigInt
. You can easily convert a string "162259276829213363391578010288127" (2**107-1 is a Mersenne prime) intoBigInt
by doingBigInt("162259276829213363391578010288127")
. It might go wrong as the name ofisProbablePrime()
method suggests. But the probability is not more than0.5^(t.bigLength)*9
.Standalone script version is 72 bytes long.
Assume we save it as "t.scala", then then program can be run as
источник
Probable
fromisProbablePrime
if Scala has anisPrime
function.Perl 5, 53 bytes
52 bytes of code + 1 for
-p
Try it online!
источник
-p
is classified as another programming language, and hence doesn't count in your bytecount.