WAP to check a given number is perfect or not
Objective
Write a C++ program to check if a given number is a Perfect number.
Algorithm / Approach
- Read an integer
n. - Run a loop
ifrom 1 up ton / 2. - Check if
iis a clean divisor:if (n % i == 0). - If it is, add
ito a runningsum. - After the loop, check if
sum == n.
main.cpp
#include<iostream>
using namespace std;
int main() {
int n, i, sum=0;
cout<<"Enter a number : ";
cin>>n;
for(i = 1; i <= n/2; i++) {
if(n%i ==0) {
sum = sum+i;
}
}
if(sum==n)
cout<< n<<" is a perfect no.";
else
cout<< n<<" is not a perfect no.";
return 0;
}
Expected Output
Enter a number : 6 6 is a perfect no.
Explanation of the Program
- A Perfect Number is a positive integer that is exactly equal to the sum of its proper divisors (excluding itself).
- For example, the divisors of 6 are 1, 2, and 3. The sum of 1+2+3 is exactly 6! Therefore, 6 is a perfect number. We only need to loop up to
N/2because no number can be evenly divided by anything larger than half of itself.
Complexity
Time Complexity
O(n) - Specifically O(n/2), which simplifies to O(n).
Space Complexity
O(1)