An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a method perfect that determines whether parameter number is a perfect number. Use this method in an application that determines and displays all the perfect numbers between 1 and 1000. Display the factors of each perfect number to confirm that the number is indeed perfect. Challenge the computing power of your computer by testing numbers much larger than 1000. Display the results
public class PerfectNumber {
public static void main(String[] args) {
perfect();
}
public static void perfect() {
int sumOfDigit = 0;
for (int i = 0; i < 1001; i++) {
sumOfDigit = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sumOfDigit = sumOfDigit + j;
}
}
if (sumOfDigit == i && sumOfDigit != 0)
System.out.print(i + "\t");
}
}
}
Comments
Leave a comment