完全數(shù):(Perfect Number)又稱完美數(shù)或完備數(shù),是一些特殊的自然數(shù)。它所有的真因子(即除了自身以外的約數(shù))的和(即因子函數(shù)),恰好等于它本身。如果一個(gè)數(shù)恰好等于它的因子之和,則稱該數(shù)為“完全數(shù)”。
需求:判斷并輸出1000以內(nèi)的所有完全數(shù)。
題目:一個(gè)數(shù)如果恰好等于它的因子之和,這個(gè)數(shù)就稱為 "完數(shù) "。例如6=1+2+3.編程 找出1000以內(nèi)的所有完數(shù)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class Wanshu { public static void main(String[] args) { int s; for ( int i= 1 ;i<= 1000 ;i++) { s= 0 ; for ( int j= 1 ;j<i;j++) if (i % j== 0 ) s=s+j; if (s==i) System.out.print(i+ " " ); } System.out.println(); } } |
方法二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class PerfectNumber { public static void main(String[] args) { System.out.println( "1000以內(nèi)的所有完數(shù)有:" ); for ( int i = 2 ; i < 1000 ; i++) { // 遍歷1000以內(nèi)的所有整數(shù) int sum = 0 ; // 定義和變量 for ( int j = 1 ; j < i; j++) { if (i % j == 0 ) { // 滿足是i的因子,就累加 sum += j; } } if (sum == i) { // 滿足因子之和等于i就打印該完數(shù) System.out.print(i + " " ); } } } } |