Perfect Number Program in JavaIn this section, we will learn what is a perfect number in Java and also create Java programs to check if the given number is perfect or not. Also, we will create a Java program for finding all the perfect numbers between the given range. The perfect number program frequently asked in Java coding tests and academics. What is a perfect number in Java?A number whose sum of factors (excluding the number itself) is equal to the number is called a perfect number. In other words, if the sum of positive divisors (excluding the number itself) of a number equals the number itself is called a perfect number. Let's understood it through an example. Example of a Perfect NumberLet's take the number 496 and heck it is a perfect number or not. First, we find the factors of 496 i.e. 1, 2, 4, 8, 16, 31, 62, 124, and 248. Let's find the sum of factors (1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 +248 = 496). We observe that the sum of factors is equal to the number itself. Hence, the number 496 is a perfect number. Similarly, we can check other numbers also. Some other perfect numbers are 6, 8128, 33550336, 8589869056, etc. Steps to Find Perfect Number
Let's implement the above steps in a Java program. Perfect Number Java ProgramsThere are the following ways to find the perfect number in Java:
Using while LoopPerfectNumberExample1.java Output 1: Enter the number: 28 28 is a perfect number. Output 2: Enter the number: 4558 4558 is not a perfect number. Using MethodPerfectNumberExample2.java Output 1: Enter the number: 6 6 is a perfect number. Output 2: Enter the number: 1234 1234 is not a perfect number. Using RecursionPerfectNumberExample3.java Output 1: Enter the number: 8128 8128 is a perfect number. Output 2: Enter the number: 7866 7866 is a perfect number. Perfect Numbers Between Given RangeThe following program finds all the perfect numbers between a given range. PerfectNumberExample3.java Output: Perfect Numbers between 2 to 10000 are: 6 is a perfect number 28 is a perfect number 496 is a perfect number 8128 is a perfect number
Next TopicSwap Two Numbers in Java Using Function
