A perfect number is a positive number greater than 1 whose factors (including 1
ID: 3642374 • Letter: A
Question
A perfect number is a positive number greater than 1 whose factors (including 1 but not the number itself) add up to the number itself.For instance, 6 is a perfect number because the factors of 6 add up to 6: 1 + 2 + 3 equals 6. Likewise, 28 is a perfect number because 1 + 2 + 4 + 7 + 14 equals 28. 26 is not a perfect number because 1 + 2 + 13 is not equal to 26.
Write a public static method called testPerfect() which takes one integer argument and returns a boolean value of true or false if the argument is or isn't a perfect number. Your method cannot simply use a switch statement or nested if-else structure to determine if it's a perfect number or not. In other words, you may not write code like the following:
if ( number == 28 || number == 496 || number == 6 || number = 8128 )
return true;
else
return false;
You must calculate the summation of the factors to see if they add up to the number itself. This method will not perform any output.
Write another public static method printFactors() that also takes an integer argument and prints out the factors of the argument in descending order (largest to smallest). By necessity, this method must perform output. Similarly to the testPerfect() method, you may not simply use and if-else statement to output the factors in this method.
If a number is a perfect number, the output should follow the format:
NUMBER:FACTORS
Thank you!
Explanation / Answer
The testPerfect method is not difficult public static boolean testPerfect(int num) { int sumOfFactors = 0; for (int i = num-1; i > 0; i--) { if (num % i == 0) { // i is a factor of num sumOfFactors += i; } } // perfect if sumOfFactors == num return sumOfFactors == num; } The function that prints the factors work in the same way. Just put a print command in the if-statement xD
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.