华为OJ平台——完美数
生活随笔
收集整理的這篇文章主要介紹了
华为OJ平台——完美数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1 import java.util.Scanner;
2
3 /**
4 *
5 * 完全數(shù)(Perfect number),又稱完美數(shù)或完備數(shù),是一些特殊的自然數(shù)。
6 * 它所有的真因子(即除了自身以外的約數(shù))的和(即因子函數(shù)),恰好等于它本身。
7 * 例如:28,它有約數(shù)1、2、4、7、14、28,除去它本身28外,其余5個(gè)數(shù)相加,1+2+4+7+14=28。
8 *
9 * 給定函數(shù)count(int n),用于計(jì)算n以內(nèi)(含n)完全數(shù)的個(gè)數(shù)
10 * @param n 計(jì)算范圍, 0 < n <= 500000
11 * @return n以內(nèi)完全數(shù)的個(gè)數(shù), 異常情況返回-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 * 統(tǒng)計(jì)小于等于n的正整數(shù)中有多少個(gè)完美數(shù)
24 * @param n
25 * @return 小于等于n的正整數(shù)中完美數(shù)的個(gè)數(shù)
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 * 判斷數(shù)x是否都是完美數(shù)
39 * @param x
40 * @return 是則返回true,否則返回false
41 */
42 private static boolean judgePerfect(int x) {
43 //end表示判斷的結(jié)束值,這樣可以提高性能,減少判斷的次數(shù)
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 }
總結(jié)
以上是生活随笔為你收集整理的华为OJ平台——完美数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 仙山小农御剑飞行方法
- 下一篇: char二维数组_C语言指针与数组详解