1 import java.util.Scanner;
2
3 /**
4 *
5 * 完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数。
6 * 它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。
7 * 例如:28,它有约数1、2、4、7、14、28,除去它本身28外,其余5个数相加,1+2+4+7+14=28。
8 *
9 * 给定函数count(int n),用于计算n以内(含n)完全数的个数
10 * @param n 计算范围, 0 < n <= 500000
11 * @return n以内完全数的个数, 异常情况返回-1
12 *
13 */
14 public class PerfectNumber {
15 public static void main(String[] args) {
16 Scanner cin = new Scanner(System.in) ;
17 int n = cin.nextInt() ;
18 cin.close();
19 System.out.println(count(n));
20 }
21
22 /**
23 * 统计小于等于n的正整数中有多少个完美数
24 * @param n
25 * @return 小于等于n的正整数中完美数的个数
26 */
27 public static int count(int n){
28 int count = 0 ;
29 for(int i = 1 ; i <= n ; i++){
30 if(judgePerfect(i)){
31 count++ ;
32 }
33 }
34 return count ;
35 }
36
37 /**
38 * 判断数x是否都是完美数
39 * @param x
40 * @return 是则返回true,否则返回false
41 */
42 private static boolean judgePerfect(int x) {
43 //end表示判断的结束值,这样可以提高性能,减少判断的次数
44 int end = x/2 ;
45 int sum = 1 ;
46 for(int i = 2 ; i <= end ; i++){
47 if(x%i == 0){
48 if(x/i == end){
49 sum = sum + end ;
50 }else{
51 sum = sum + i + end ;
52 }
53 end = x/(i+1) ;
54 }
55 }
56 if(sum == x){
57 return true ;
58 }else{
59 return false;
60 }
61 }
62 }