
A number is perfect if it is equal to the sum of its proper divisors (i.e., not counting itself). For example, 6 = 1 + 2 + 3 and 28 = 1 + 2 + 4 + 7 + 14 are the first two perfect numbers.
The following program prints all perfect numbers between 1 to 100.
// Mukesh Tekwani class PerfectNumbers { public static void main(String [] args) { int n; //number which is to be checked for(n = 1; n <= 100; n++) { if (isPerfectNum(n)) System.out.println(n + " is a perfect number"); } } static boolean isPerfectNum(int n) { int sum = 0, i; for(i = 1; i < n; i++) { if (n % i == 0) sum = sum + i; } if (sum == n) return true; else return false; } }
Advertisements