Java (perfect numer)

2007-10-20 6:28 pm
Write a program to get first four perfect number (included the main part)
更新1:

120好似不是第三個perfect number...根據供給的網站...是嗎?.?~~

回答 (1)

2007-10-21 2:13 am
✔ 最佳答案
其實好簡單,不過你要識咩叫perfect number。
一個perfect number既所有因數加埋必須等於它的兩倍。

6就係一個perfect number,因為 1 + 2 + 3 + 6 = 12 = 2 x 6。
28又係一個perfect number,因為 1 + 2 + 4 + 7 + 14 + 28 = 56 = 2 x 28。

數論裏已經證明,如果一個number係even perfect number,它必定能寫成2m-1(2m-1)

所以我們可以用下列數行Java程序寫出來。


/** Program for searching perfect numbers */
public class Program {
 public static void main(String[] args) {
  int power = 2;
  for (int i = 0; i < 4; i++) {
   int nextPower = power * 2;
   System.out.println((nextPower - 1) * power);
   power = nextPower;
  }
 }
}

頭四個perfect numbers係:

6
28
120
496
祝你好運。

2007-10-22 20:01:13 補充:
You are right, I will modify the program to fit the requirements.

2007-10-25 01:14:12 補充:
With limited space for updating, I will just describe the approach, which is simple. Replace i by primes[i] by a hard-coded prime number array [2,3,5,7] then we solved the problem.


收錄日期: 2021-04-23 17:22:14
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20071020000051KK01087

檢視 Wayback Machine 備份