LeetCode - Algorithms - 507. Perfect Number

Problem

507. Perfect Number

Java

my solution

There is one fact that odd perfect numbers are greater than \( 10^{1500} \) if exist. By Euclid–Euler theorem, there is a one-to-one relationship between even perfect numbers and Mersenne primes. Even perfect number have the form as \( 2^{p−1}(2^p−1) \).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public boolean checkPerfectNumber(int num) {
if ((num & 1) == 1)
return false;
else {
if (num == 0)
return false;
int n = num;
int p = 0;
for (; (n & 1) == 0; p++) {
n = n >> 1;
}
int x = (2 << (p - 1)) * ((2 << p) - 1);
return num == x;
}
}
}

Submission Detail

  • 156 / 156 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Perfect Number.
  • Memory Usage: 37.7 MB, less than 23.24% of Java online submissions for Perfect Number.