zoukankan      html  css  js  c++  java
  • 完美數

    完美數

    完美數的定義為

    某一個數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+" ");
            }
       }
       
    }
  • 相关阅读:
    迷宫的最短路径(bfs)
    INNODB引擎概述
    mysql-innodb的事务日志
    python-set集合
    一个python代码练习
    关于arm 的字节对齐
    学习嵌入式为什么要有uboot(深度解析)
    uboot 添加 自定义命令
    关于UBOOT,LINUX内核编译,根文件系统的15个小问题
    s5p6818 Overview
  • 原文地址:https://www.cnblogs.com/bmbi/p/5248133.html
Copyright © 2011-2022 走看看