Program to check the Number is Perfect Number of Not
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
- 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 ofn
.
- We have a variable
- 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 ofn
. - Inside the loop, we check if
n
is divisible by the current numberi
. If it is, theni
is a proper divisor ofn
, and we add it to thesum
.
- We use a for loop to iterate through the numbers from 1 to
- Check for Perfection:
- After the loop, we compare the value of
sum
withn
. - If
sum
is equal ton
, thenn
is a perfect number, and we print “Number is Perfect Number”. - Otherwise, if
sum
is not equal ton
, thenn
is not a perfect number, and we print “Number is Not Perfect Number”.
- After the loop, we compare the value of
- 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