163.Perfect Number
阿新 • • 發佈:2018-09-12
returns cee == divisor amp 我們 als 數字 整數
題目:
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
我們定義Perfect Number是一個正整數,它等於除了它自己之外的所有正除數的總和。
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
現在,給定一個整數n,編寫一個函數,當它是一個完美數字時返回true,否則返回false。
Example:
Input: 28 Output: True Explanation: 28 = 1 + 2 + 4 + 7 + 14
Note: The input number n will not exceed 100,000,000. (1e8)
解答:
1 class Solution { 2 public boolean checkPerfectNumber(int num) { 3 if(num==1) return false; 4 int sum=1; //1一定是sum的因子 5 for(int i=2;i*i<=num;i++){6 if(num%i==0) sum+=i+num/i; //i是num的因子,則sum/i也是sum的因子,都加上 7 if(i*i==num) sum-=i; //如果num是完全平方數,則i加了兩次,減去一次 8 } 9 return sum==num; 10 } 11 }
詳解:
163.Perfect Number