Contact Learn C
Copy Program Share Program

Program 29:To know whether the given number is perfect number or not

Program 29: What is Perfect Number?
#include<stdio.h>
#include<math.h>
main()
{
  int num,i,sum=0;
  printf("Enter a number to know whether it is perfect or not\n");
  scanf("%d",&num);
  for(i=1;i<num;i++)
  {
    if(num%i==0)
    {
      sum+=i;
    }
  }
  if(sum==num)
  {
    printf("The given number %d is perfect\n",num);
  }
  else
  {
    printf("The given number %d is not perfect because the sum of its divisors are %d\n",num,sum);
  }
}
Explanation:
  1. The program starts with initializing :
    • num → To store input from user
    • i → used as helping variable
    • sum → To store output
  2. printf("Enter a number to know whether it is perfect or not\n");
    scanf("%d",&num);
    Takes input from user and is stored in num. Lets take num=6
  3. for(i=1;i<num;i++)
    {
    if(num%i==0)
    {
    sum+=i;
    }
    }
    This is the main logic of this program.Lets take num=6
    • Iteration 1: i=1,1<6; which is true so the loop executes
      • num%i → 6%1=0→0==0 which is true so if part is executed
        • sum+=i → sum=0+1→sum=1
        • Now i increments by 1 so i=2
    • Iteration 2: i=2,2<6; which is true so the loop executes
      • num%i → 6%2=0→0==0 which is true so if part is executed
        • sum+=i → sum=1+2→sum=3
        • Now i increments by 1 so i=3
    • Iteration 3: i=3,3<6; which is true so the loop executes
      • num%i → 6%3=0→0==0 which is true so if part is executed
        • sum+=i → sum=3+3→sum=6
        • Now i increments by 1 so i=4
    • Iteration 4: i=4,4<6; which is true so the loop executes
      • num%i → 6%4=2→2==0 which is flase so if part is not executed
        • sum+=i → sum=6(remains same)
        • Now i increments by 1 so i=5
    • Iteration 5: i=5,5<6; which is true so the loop executes
      • num%i → 6%5=1→1==0 which is flase so if part is not executed
        • sum+=i → sum=6(remains same)
        • Now i increments by 1 so i=6
    • Iteration 6: i=6,6<6; which is flase so the loop terminates
  4. The final output which is stored in sum=6
  5. if(sum==num)
    {
    printf("The given number %d is perfect\n",num);
    
    }
    else
    {
    printf("The given number %d is not perfect because the sum of its divisors are %d\n",num,sum);
    }
    Now sum is compared with the original number given as input ans if they are equal then it is a perfect number else not
  6. As sum=6 and num=6 so 6 is a perfect number.
  7. The divisors of 6 are 1,2,3 and the sum is 1+2+3=6 so sum and number is same which is why it is perfect number
  8. If we take 8 as number its divisors are 8=1,2,4 and its sum is 1+2+4=7 which is not equal to the input we gave.

 Output:

To know whether the given number is perfect number or not

  

No comments:

Post a Comment

Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide