题目:
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
Example:
Input: 28 Output: True Explanation: 28 = 1 + 2 + 4 + 7 + 14
Note: The input number n will not exceed 100,000,000. (1e8)
分析:
class Solution {
public boolean checkPerfectNumber(int num) {
//判断一个数是否满足完美数(即其等于它的所有除数之和,除他本身之外)
//思路:判断一个数是否是完美数有以下几点性质:
//1.所有的完全数都是三角形数。6=1+2+3;28=1+2+3+...+6+7;496=1+2+3+...+30+31;8128=1+2+3…+126+127。
//2.完全数都是以6或8结尾。如果以8结尾,那么就肯定是以28结尾
//3.各位数字辗转式相加个位数是1。除6以外的完全数,把它的各位数字相加,直到变成个位数,那么这个个位数一定是1。例如:28:2+8=10,1+0=1;496:4+9+6=19,1+9=10,1+0=1;8128:8+1+2+8=19,1+9=10,1+0=1;33550336:3+3+5+5+0+3+6=28,2+8=10,1+0=1。
//4.它们被3除余1、被9除余1、1/2被27除余1。除6以外的完全数,它们被3除余1,9除余1,还有1/2被27除余1。28/3 商9余1,28/9 商3余1,28/27 商1余1。496/3 商165余1,496/9 商55余1。8128/3 商2709余1,8128/9 商903余1,8128/27 商301余1。
//5.枚举法:6 28 496 8128 33550336
if(num<=1) return false;
//采用性质1
//二元一次方程求解
if(num==6) return true;
//判断结果是否是整数%1(需要满足多个条件性质)
return ((Math.sqrt(1+8.0*num)-1)/2)%1==0&&(num%10==6||num%10==8)&&(num%3==1||num%9==1);
}
}