2008年8月29日 星期五

找出1~2000中所有的Perfect number

Perfect number 是指某一個數,其因數相加會等於其數
code
package javahomework;

import javax.swing.JOptionPane;

public class HW05 {
 public static void main(String args[]) {
  String Screen = "The PerfectNumber is ";
  for (int j = 4; j < 2000; j++) {
   if (AD(j) == j)
    Screen = Screen + j + ",";
  }
  JOptionPane.showMessageDialog(null, Screen);
 }

 static int AD(int n) {
  int ans = 1;
  for (int i = 2; i < n; i++) {
   if (n % i == 0)
    ans = ans + i;
  }
  return ans;
 }
}

沒有留言: