Google Add

Search

Perfect Number Program in C, C++

Write a C, C++ program to check whether a given number is perfect or not. We have to write a program to check whether a input number is perfect.

Perfect Number

A perfect number, is a positive integer that is equal to the sum of its proper divisors.

For example - 6 is a perfect number.

6  = 1 + 2 + 3 (1,2,3 is it's factors).

Similarly 28 is a perfect number.

28 = 1 + 2 + 4 + 7 + 14

Let's take another example of 12. Factors of 12 is 1, 2, 3, 4, 6.

1 + 2 + 3+ 4 + 6 = 16. So we can conclude that 12 is not a perfect number.

Print factors of a number

C, C++ Interview Questions

Print prime numbers between 1 to 100

Perfect Number Program in C


#include <stdio.h>

int main(void) {

   int num, i=1, sum=0;
 
   printf("Enter number \n");
   scanf("%d",&num);
 
  /* Check if entered number is greater than zero. */
 
   if( num > 0){
  
     while(i < num){
     
        if(num % i==0){
          sum = sum + i;
        }
      
        i++;
     }
    
     /* If entered number is equal to it's proper divisiors. */
    
      if(sum == num){
     
          printf("\n %d is a perfect number",i);

       } else {
     
         printf("\n %d is not a perfect number",i);
      
       }  
  
  } else {
  
     printf("Perfect number should be greater than zero");
 
   }
 
 return 0;
}

Output :

Enter number : 6

6 is a perfect number

Enter number : 23

23 is not a perfect number

Perfect Number Program in C++


#include <iostream>
using namespace std;

int main() {
 
   int num, sum = 0;
 
   cout << " Enter a number to check whether it's a perfect or not \n";
   cin >> num;
 
 
   for (int i = 1; i < num; i++) {
     
       
     if (num % i == 0) {
   
        sum = sum + i;
   
     }
   }
 
   if ( sum == num) {
  
      cout << num << " is a Perfect number";
  
   } else {
  
      cout << num << " is not a Perfect number";
  
   }
 
   return 0;
}

No comments:

Post a Comment