Frequently Asked Java Program 28: Java Program to Find if Given Number Is a Perfect Number
A Perfect number is a positive integer that is equal to the sum of its proper divisors excluding the number itself.
For Example: Take Number 6. Its divisors are 1, 2 , 3 and 6. When we add all divisors except 6 ( as it is number itself) (i.e. 1+2+3= 6), it is equal to actual number. So we can say Number 6 is a perfect number.
The smallest perfect number is 6. Other perfect numbers are 28, 496, and 8,128.
Logic:
- When we divide a number say X by other number say Y and reminder is zero, then number Y is a proper divisor. All proper divisor of a number X are between 1 and X/2. ( 1 and X/2 are included) . To find the proper divisor we need to divide the number by 1 to number/2.
- We need to keep adding all divisors.
Java Program:
package StringPrograms; import java.util.Scanner; public class PerfectNumber { public static void perfectNumber(int userInput) { // Handling numbers less than or equal to zero if(userInput