Perfect Number

Definition & Explanation

A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). In other words, a perfect number is a number that is half the sum of all its positive divisors (excluding itself).

For example, the number 28 is a perfect number because the sum of its proper divisors (excluding itself) is equal to 1 + 2 + 4 + 7 + 14 = 28.

Logic

  1. Input:
    • We have a variable n assigned the value 28, which is the number we want to check for perfection.
    • We initialize a variable sum to 0, which will store the sum of the proper divisors of n.
  2. Loop through Proper Divisors:
    • We use a for loop to iterate through the numbers from 1 to n - 1. These are the potential proper divisors of n.
    • Inside the loop, we check if n is divisible by the current number i. If it is, then i is a proper divisor of n, and we add it to the sum.
  3. Check for Perfection:
    • After the loop, we compare the value of sum with n.
    • If sum is equal to n, then n is a perfect number, and we print “Number is Perfect Number”.
    • Otherwise, if sum is not equal to n, then n is not a perfect number, and we print “Number is Not Perfect Number”.
  4. Output:
    • Depending on the comparison result, the program prints whether the given number is a perfect number or not.
C

Method 1 :

#include <stdio.h>

int main() {
    int n = 28; // Number to check
    int sum = 0;

    for (int i = 1; i < n; ++i) {
        if (n % i == 0) {
            sum += i;
        }
    }

    if (sum == n) {
        printf("Number is Perfect Number\n");
    } else {
        printf("Number is Not Perfect Number\n");
    }

    return 0;
}

Output :

C++

Method 1 :

#include <iostream>

using namespace std;

int main() {
    int n = 28; // Number to check
    int sum = 0;

    for (int i = 1; i < n; ++i) {
        if (n % i == 0) {
            sum += i;
        }
    }

    if (sum == n) {
        cout << "Number is Perfect Number" << endl;
    } else {
        cout << "Number is Not Perfect Number" << endl;
    }

    return 0;
}

Output :

JAVA

Method 1 :

public class Main {
    public static void main(String[] args) {
        int n = 28; // Number to check
        int sum = 0;

        for (int i = 1; i < n; ++i) {
            if (n % i == 0) {
                sum += i;
            }
        }

        if (sum == n) {
            System.out.println("Number is Perfect Number");
        } else {
            System.out.println("Number is Not Perfect Number");
        }
    }
}

Output :

Python

Method 1 :

n=28
sum=0
for i in range(1,n):
	if n%i==0:
		sum+=i

if sum==n:
	print("Number is Perfect Number")
else:
	print("Number is Not Perfect Number")

Output :

Number is Perfect Number