考研机试 20.完数VS盈数

时间:2021/03/03

一.题目描述

一个数如果恰好等于它的各因子(该数本身除外)子和,如:6=3+2+1。则称其为“完数”;若因子之和大于该数,则称其为“盈数”。 求出2到60之间所有“完数”和“盈数”。

输入描述

题目没有任何输入。

输出描述

输出2到60之间所有“完数”和“盈数”,并以如下形式输出:
E: e1 e2 e3 ......(ei为完数)
G: g1 g2 g3 ......(gi为盈数)
其中两个数之间要有空格,行尾不加空格。

题目链接

https://www.nowcoder.com/practice/ccc3d1e78014486fb7eed3c50e05c99d?tpId=40&tqId=21351&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking&tab=answerKey

二.算法

题解

编写一个函数计算出该数的所有因子,具体计算方法是先将输入开平方,然后进行循环,若能将输入整除,则为该输入的因子,注意:如果一个数的平方是输入值,则该值只能算为一个,不能重复存入,这是最容易出错的一点,比如2*2=4,则2是4的因子,但只能有存入一个2,否则会重复。

代码

import java.util.LinkedList;

public class Main{

    public static void main(String[] args){

        LinkedList<Integer> e = new LinkedList<>();    //完数
        LinkedList<Integer> g = new LinkedList<>();    //盈数

        for(int i = 2; i <= 60; i++){
            LinkedList<Integer> factor = divisor(i);
            int count = 0;

            for(int a : factor){
                count += a;
            }

            if(count == i){
                e.add(i);
            }
            else if(count > i){
                g.add(i);
            }
        }

        System.out.print("E: ");
        for(int i : e){
            System.out.print(i + " ");
        }
        System.out.println();

        System.out.print("G: ");
        for(int i : g){
            System.out.print(i + " ");
        }
        System.out.println();
    }

    public static LinkedList<Integer> divisor(int a){

        LinkedList<Integer> factor = new LinkedList<>();
        long b = (int)Math.sqrt(a);

        factor.add(1);

        for(int i = 2; i <= b; i++){

            if(a % i == 0){
                factor.add(i);
                if(i != (a / i)){
                    factor.add(a / i);
                }
            }
        }

        return factor;
    }
}
原文地址:https://www.cnblogs.com/machi12/p/14476462.html