Perfect Number in Java


A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. Using for the for loop and if condition statement. A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line. The if statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true.
Example :
6 is a perfect number because 6 is divisible by 1, 2 and 3 and the sum of these values is 1 + 2 + 3 = 6. Remember, we have to exclude the number itself.

Source Code

import java.util.Scanner;
public class perfect {
    //Write a program to check the given number is perfect number or not.
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter The Number : ");
        int n = in.nextInt();//6
        int sum=0;
        for (int i = 1; i <n; i++) {
            if(n%i==0){
                sum+=i;//1+2+3
            }
        }
        if(sum==n){
            System.out.println(n + " is a Perfect Number");
        }else {
            System.out.println(n + " is not a Perfect Number");
        }
    }
}
 

Output

Enter The Number : 6
6 is a Perfect Number
Enter The Number : 13
13 is not a Perfect Number
To download raw file Click Here

Basic Programs