Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Answer

added 1206 characters in body
Source Link
Dennis
  • 211.7k
  • 41
  • 380
  • 830

Python 3 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.

Python 3, 45 bytes

lambda n:-~n&n<all(n%i for i in range(2,n))<n

Try it online!

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.

Source Link
Dennis
  • 211.7k
  • 41
  • 380
  • 830

Python 3, 45 bytes

lambda n:-~n&n<all(n%i for i in range(2,n))<n

Try it online!

AltStyle によって変換されたページ (->オリジナル) /