As @hivert points out, the solution below assumes that perfect numbers are even. In fact, it is not known whether any odd perfect number exists, however there is a lot of information pointing to there being no odd perfect numbers. (https://en.wikipedia.org/wiki/Perfect_number#Odd_perfect_numbers).
For starters, we must have N > 101500. With that, we will proceed with the even case.
An even number is perfect if it has the following form:
2p - 1 * (2p - 1), where p is a Mersenne prime.
We will need a prime number checker handy to do this efficiently. Fortunately, this is a very popular topic and there are very many existing functions in the wild for doing this. For example, the answer provided @Alexandru to the question How to create the most compact mapping n → isprime(n) up to a limit N? is a very nice and straightforward python implementation. However, if we are going for pure speed, we will need to employ alternative methods, such as Miller Rabin. This is provided in the library sympy
And here is our very efficient perfect even number checker:
from sympy.ntheory import isprime
def IsPerfect(N):
## First get the number of 2's that divide N
## If there are none, the number is not perfect
p = 0
while N % 2 == 0:
N = N >> 1
p += 1
if p == 0:
return False
q = 2**(p + 1) - 1
if N != q:
return False
if isprime(N):
return True
else:
return False
Here are some examples:
IsPerfect(137438691328)
True
IsPerfect(33550336)
True
## Note 11 is not Mersenne
2**(11 - 1) * (2**11 - 1)
2096128
IsPerfect(2096128)
False
IsPerfect(2658455991569831744654692615953842176) ## instant on my laptop
True
Here are all of the primes less than 100:
mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89]
not_mersenne = [11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97]
[IsPerfect(2**(p - 1) * (2**p - 1)) for p in mersenne]
[True, True, True, True, True, True, True, True, True, True]
[IsPerfect(2**(p - 1) * (2**p - 1)) for p in not_mersenne]
[False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]