欢迎来到码农小陈的博客

完美數

完美數

完美數的定義為

某一個數n等於自己以外的正因數的總和則稱n為完美數

例如:

6除了6本身的正因數有1,2,3

1+2+3=6,則6就是一個完美數

 

請寫一個程式來判斷輸入的資料是否為完美數,並將輸入資料中為完美數的部分輸出

 

input

資料格式如下:

第一個數字為待測的資料個數

例如以下範例中第一個數字為10,則表示後面有10筆資料需要讀入

 

output

而輸出部分只需印出檢測結果為完美數的數字就好

輸入與輸出方式皆為console讀入/印出

例如C++中的cin/cout, 而非讀檔寫檔

另外input的大小可能會達9位數

 

Sample input:

10

2 3 28 4 7 9 13 6 27 65536

 

Sample output:

28 6


 

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Perfect_Number   {
   public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    //输入一个要测试多少数
    int num = scan.nextInt();
    int c;
    List<Integer> result = new ArrayList<Integer>();
    
    for(int i=0;i<num;i++){
        c=scan.nextInt();
        if(isPerfect(c)){
            result.add(c);
        }
    }
   playResult(result);    
    
}
   
   public static Boolean isPerfect(int n){
       int a = n;
        int sum = 0;
                for (int i = 1; i <n; i++) { 
                    if (n % i == 0) { 
                        sum+=i;
                    }
                }    
             return sum==a;
            }
   
   public static void playResult(List<Integer> result){
       for(int j:result){
            System.out.print(j+" ");
        }
   }
   
}

 

posted on 2016-03-06 18:16  码农小陈  阅读(150)  评论(0编辑  收藏  举报

导航