16 May 2024

Perfect Number

Given an integer input as the number, the objective is to check whether or not the number can be represented as the sum of its factors except the number itself. Therefore, we write a code to Check Whether or Not a Number is a Perfect Number in Java Language

Perfect Number

A Perfect Number is a positive integer that equals the sum of its proper divisors (factors excluding the number itself).

For example:

  • 6 is a perfect number because 1+2+3=61 + 2 + 3 = 6.
  • 28 is also a perfect number because 1+2+4+7+14=281 + 2 + 4 + 7 + 14 = 28.


import java.util.*;


class HelloWorld {

    public static void main(String[] args) {

        int n=sc.nextInt();

        int sum=0;

        for(int i=1;i<n;i++){

            if(n%i==0){

                sum+=i;

            }

        }

        System.out.print(n%sum==0?"yes":"no");

        }

    }

}

How It Works

  1. Input:
    The program reads an integer nn from the user.

  2. Find Proper Divisors:

    • A proper divisor of nn is any number less than nn that divides nn without a remainder.
    • Use a for loop from 1 to n1n-1 to check all possible divisors.
  3. Sum the Divisors:

    • Add each divisor to a variable sum.
  4. Check for Perfection:

    • Compare sum with nn.
    • If sum == n, the number is perfect; otherwise, it’s not.
  5. Output:

    • Print "Yes" if the number is perfect, and "No" otherwise.

Example Input and Output

Example 1
Input:
6
Process:

  • Proper divisors of 6 are 1,2,31, 2, 3.
  • Sum = 1+2+3=61 + 2 + 3 = 6.

Output:

Yes, 6 is a perfect number.

Example 2
Input:
10
Process:

  • Proper divisors of 10 are 1,2,51, 2, 5.
  • Sum = 1+2+5=81 + 2 + 5 = 8.

Output:

No, 10 is not a perfect number.

Edge Cases

  1. Smallest Perfect Number:
    The smallest perfect number is 6.

  2. Prime Numbers:
    Prime numbers can never be perfect numbers because their only proper divisor is 1.

  3. Negative Numbers:
    Perfect numbers are defined only for positive integers.

No comments:

Post a Comment