华为OJ平台——完美数
生活随笔
收集整理的這篇文章主要介紹了
华为OJ平台——完美数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 }
總結
以上是生活随笔為你收集整理的华为OJ平台——完美数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 仙山小农御剑飞行方法
- 下一篇: char二维数组_C语言指针与数组详解