How to Check If a Given Number Is Perfect Number in Java


In this example, we will learn how to find the given number is perfect number or not in Java.

Source Code

package com.beginner.examples;

public class PerfectExample {
     
    public static void main(String[] args){
    	// It is the number to be checked.
        int number = 153;
        int sum = 0;
        for(int i = 1; i <= number/2; i++){
            if(number%i == 0){
                sum += i;
            }
        }
        if(sum == number)
            System.out.println(number + " is a perfect number.");
        else
            System.out.println(number + " is not a perfect number.");
      }
}

Output:

153 is not a perfect number.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments