Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to check a given number is perfect or not

C++ Code Example — Loop Programs

ADVERTISEMENT

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

  1. Read an integer n.
  2. Run a loop i from 1 up to n / 2.
  3. Check if i is a clean divisor: if (n % i == 0).
  4. If it is, add i to a running sum.
  5. 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/2 because 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)
ADVERTISEMENT