In this article, we will understand how to check whether a number is perfect number or not. Perfect number is a positive integer that is equal to the sum of its factors other than itself.
Below is a demonstration of the same −
Input
Suppose our input is −
Enter the number : 496
Output
The desired output would be −
The number 496 is a perfect number
Algorithm
Step 1 - START Step 2 - Declare two long values namely my_input, my_sum and an integer value 'i'. Step 3 - Read the required values from the user/ define the values Step 4 - Using a while condition, iterate until it reaches the specified condition. Step 5 - Check of the value 'my_input % i' leaves no reminder. If yes, add ‘my_sum’ to 'i' and assign it to 'my_sum'. Increment 'i' value. Step 6 - If the 'my_sum' value is equal to the input, it's a perfect number, else it's not a perfect number Step 7 - Display the result Step 8 - Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in our coding ground tool .
import java.util.Scanner; public class PerfectNumber{ public static void main(String args[]){ long my_input, my_sum; int i; my_sum=0; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter the number : "); my_input = my_scanner.nextLong(); i=1; while(i <= my_input/2){ if(my_input % i == 0){ my_sum = my_sum + i; } i++; } if(my_sum==my_input) System.out.println("The number " +my_input+" is a perfect number"); else System.out.println("The number " +my_input+" is not a perfect number"); } }
Output
Required packages have been imported A reader object has been defined Enter the number : 496 The number 496 is a perfect number
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
import java.util.Scanner; public class PerfectNumber{ public static void main(String args[]){ long my_input, my_sum; int i; my_sum=0; my_input = 496; System.out.println("The number is defined as " +my_input); i=1; while(i <= my_input/2){ if(my_input % i == 0){ my_sum = my_sum + i; } i++; } if(my_sum==my_input) System.out.println("The number " +my_input+" is a perfect number"); else System.out.println("The number " +my_input+" is not a perfect number"); } }
Output
The number is defined as 496 The number 496 is a perfect number