Java Program to Check Perfect Number or Not

  • Write a java program to check whether a number is perfect number or not.

A perfect number is a number whose sum of all the divisors is equal to the number itself.
Examples of Perfect Numbers :
6 = 1 + 2 + 3, (1, 2 and 3 are proper divisors of 6).
28 = 1 + 2 + 4 + 7 + 14 (1, 2, 4, 7, 14 are proper divisors of 28).

In this java program, we have to check whether a given number is an perfect number or not and print the result on screen.

Algorithm to check a number is perfect number or not
Let N be the given number.
  • Find all divisors of a N between 1 to N/2.
  • Add the values of all divisors to a variable sum.
  • If sum is equal to N, then N is a perfect number otherwise not a perfect number.

Java program to check perfect number or not

This program first takes a number as input from user and stores it in variable 'N'. Using a for loop, we iterate from 1 to N/2 to find the sum of all divisors of N. If divisor sum is equal to N, then N is a perfect number else not a perfect number.

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to check a number is perfect number or not
 */
public class PerfectNumber {
    public static void main(String[] args) {
        int N, i, divSum;
        Scanner scanner;
        scanner = new Scanner(System.in);

        System.out.println("Enter an Integer");
        N = scanner.nextInt();

        /*
         * Find the sum of all divisors of a N between 1 to N/2
         */
        for (divSum = 0, i = 1; i <= N / 2; i++) {
            if (N % i == 0) {
                divSum += i;
            }
        }

        /*
         * Check if divSum is equal to N. If true then N is Perfect Number
         */
        if (divSum == N)
            System.out.format("%d is Perfect Number", N);
        else
            System.out.format("%d is Not a Perfect Number", N);
    }
}
Output
Enter an Integer
6
6 is Perfect Number
Enter an Integer
12
12 is Not a Perfect Number

Recommended Posts
Java Program to Check a Number is Prime Number or Not
Java Program to Check Whether a Number is Armstrong Number or Not
Java Program to Check Whether a Number is Palindrome or Not
Java Program to Check If a Year is Leap Year or Not
Java Program to Calculate Simple Interest
Java Program to Calculate Compound Interest
Java Program to Convert Celsius to Fahrenheit
Java Program to Convert Decimal to Binary Numbers
Java Program to Find LCM and GCD of Two Numbers
Java Program for Matrix Multiplication
Java Program to Find Volume and Surface Area of Cuboid
All Java Programs