此题初看比较简单,如果思路不一样可能会造成代码复杂。请认真思考。

要求:(可以选择1,或者2及以后的任一个!)

  1. 输出1 - 1000间的所有完数;

  2. 输出给定区间的所有完数;☆

  3. 输出给定区间的所有完数,并给出是这些完数中的第几个数;☆

  4. 在 3 的基础上,使得输出的完数格式如: 6 = 1 + 2 + 3。★


好了这里给出第4题的输出实例:

Please input the section [M,N]
M = 1
N = 1000
The follow will print the End of a few from 1 to 1000
The 1`st End of a few is :6=1+2+3
The 2`st End of a few is :28=1+2+4+7+14
The 3`st End of a few is :496=1+2+4+8+16+31+62+124+248


下面的程序是第四个的,请仔细考虑上面的4小题,再看下面的代码。



/**
 * project  51CTO
 * package  base.wong
 * fileInfo End_OF_A_Few.java  2014-4-13 下午10:20:52
 * author   WANGXIN
 * aim      TODO
 */
package base.wong;
import java.util.Scanner;
/**
 * @author WANGXIN by 2014-4-13下午10:20:52
 * @version v1.0
 * aim:print the End of a few.
 * The so-called End of a few refers to a
 * number of precisely equivalent to it and all the factors
 */
public class End_OF_A_Few {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input the section [M,N]");
        System.out.print("M = ");
        int M = sc.nextInt();
        System.out.print("N = ");
        int N = sc.nextInt();
        System.out.println("The follow will print the End of a few from " + M
                + "to " + N);
        showNumber(M, N);
    }
    /**
     *
     * @param M
     *            the upper limit of the specific Number
     * @param N
     *            the lower limit of the specific Number
     */
    public static void showNumber(int M, int N) {
        int factor;
        int count = 0;
        int flags;
        int flags2;
        for (int i = M; i <= N; i++) {
            factor = 0;
            flags = 0;
            for (int j = 1; j < i; j++) {
                if (i % j == 0) {
                    factor += j;
                    flags++;
                }
            }
            if (i == factor) {
                count++;
                System.out.print("The " + count + "`st End of a few is :"
                        + factor + "=");
                factor = 0;
                flags2 = 0;
                for (int j = 1; j < i; j++) {
                    if (i % j == 0) {
                        flags2++;
                        if (flags2 < flags)
                            System.out.print("" + j + "+");
                        if (flags2 == flags)
                            System.out.print(j);
                    }
                }
                System.out.println();
            }
        }
    }
}