Problem:
A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect number because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. There are four perfect numbers less than 10000. Write a program to find all these four numbers.
Output:
6
28
496
8128
28
496
8128
Solution:
public class PerfectNumbers { public static int sumDivisors(int n ) { int sum = 0; for (int i =n-1;i>=1;i--) { if(n%i == 0) { sum+=i; } } return sum; } public static void main(String[] args) { for (int i =1;i<10000;i++) { if(sumDivisors(i) == i) System.out.println(i); } } }
No comments:
Post a Comment