輸出特定區間的所有完數 面試算法(2)

此題初看比較簡單,如果思路不一樣可能會造成代碼複雜。請認真思考。

要求:(可以選擇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();
            }
        }
    }
}

   



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章