完美数字显示Java

时间:2015-11-17 14:36:00

标签: java

我对家庭作业有以下问题

  

如果一个数字等于除其自身之外的所有因子的总和,则它是一个完美的数字。例如,6是一个完整的数字,因为6 = 1 + 2 + 3。

     

编写一个带有输入数字的程序,并显示所有完整的数字,包括该数字。

这就是我到目前为止所拥有的

import java.util.*;
public class perfectnumbers
 {
public static void main(String[] args){
   Scanner console = new Scanner(System.in);

   int externalNumber;

   int internalNumber;
   int internalTotal = 0;

   System.out.println("Input Number");
   externalNumber = console.nextInt();

   while (externalNumber > 0) {
       internalNumber = externalNumber;
       while (internalNumber > 0) {
           internalNumber = internalNumber - 1;
           internalTotal = internalNumber + internalTotal;
        }
        if (internalTotal == externalNumber) {
            System.out.println(internalTotal);
        }
        externalNumber = externalNumber - 1;
        internalTotal = 0;
    }
}
}

但是出于某种原因,当我输入一个数字时只输出3个......有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

完美数字(与其他完美事物一样)非常稀缺

https://oeis.org/A000396

它们(在int范围内):

6, 28, 496, 8128, 33550336

(使用8589869056, 137438691328, 2305843008139952128时,只有三个 long

所以你可以这样实现它:

  private static int[] perfectNumbers = new int[] {
    6, 28, 496, 8128, 33550336
  };

  private static void displayPerfects(int upTo) {
    for (int item : perfectNumbers) 
      if (item > upTo)
        break;
      else {
        System.out.print(item); 
        System.out.println();
      }
  }

  ...

  public static void main(String[] args) {  
    ...
    System.out.println("Input Number");
    ...
    externalNumber = console.nextInt();
    ...
    displayPerfects(externalNumber);
  }

请注意,效率在您的情况下非常重要,例如如果你给出了2000000000,你需要花多少时间?您所要做的就是最多测试五个值

答案 1 :(得分:1)

你永远不会检查一个因素。做这样的事情:

while (externalNumber > 0) {
    internalNumber = externalNumber-1;  //Make sure to subtract one here
    while (internalNumber > 1) { //Change this to 1 so you don't divide by 0
        internalNumber = internalNumber - 1;
        if (externalNumber%internalNumber==0){ //Check for factor
            internalTotal = internalNumber + internalTotal;
        }
    }
    if (internalTotal == externalNumber) {
        System.out.println(internalTotal);
    }
    externalNumber = externalNumber - 1;
    internalTotal = 0;
}