C Example Perfect Number

What is perfect number? 

 Perfect number is a positive number which sum of all positive divisors excluding that number is equal to that number. 

  • For example 6, divisor of 6 are 1, 2 and 3. 
    • Sum of its divisor is  1 + 2+ 3 =6
    • Note: 6 is the smallest perfect number. 
  • 1+ 2 + 4 + 7 + 14 = 28
  • Some more perfect numbers: 496, 8128 

Where is it Used? (Real-world use cases)

In real life, perfect numbers don’t have direct industrial applications (like sorting or factorials do),
but they are very important in mathematics, research, cryptography, and learning programming.

  1. Mathematics & Number Theory
    • Studied for thousands of years (dating back to Euclid, 300 BC).
    • Connected with Mersenne primes (special prime numbers).
  2. Cryptography
    • Some encryption algorithms rely on prime and related special numbers (perfect numbers have links with Mersenne primes).
  3. Computer Science (Algorithms & Puzzles)
    • Used in problem-solving, coding challenges, and teaching loops, recursion, and divisor algorithms.
  4. Error Detection in Systems
    • Certain checksum techniques use divisor properties (though rare, perfect numbers appear in some mathematical formulations).
  5. Mathematical Beauty & Research
    • Perfect numbers are rare and special → used for exploring properties of integers.

Example Code 1: 

#include<stdio.h> 
int main()
{ 
  int n,i=1,sum=0; 
  printf("Enter a number: "); 
  scanf("%d",&n); 
  while(i<n){ 
      if(n%i==0) 
           sum=sum+i; 
          i++; 
  } 
  if(sum==n) 
      printf("%d is a perfect number",i); 
  else 
      printf("%d is not a perfect number",i); 
  return 0; 
} 

/* 
Sample output: 
Enter a number: 6 
6 is a perfect number 
*/

Code 2: 

#include<stdio.h> 
int main(){ 
  int n,i,sum; 
  int min,max; 
  printf("Enter the minimum range: "); 
  scanf("%d",&min); 
 printf("Enter the maximum range: "); 
  scanf("%d",&max); 
  printf("Perfect numbers in given range is: "); 
  for(n=min;n<=max;n++){ 
    i=1; 
    sum = 0; 
    while(i<n)
  { 
      if(n%i==0) 
           sum=sum+i; 
          i++; 
    } 
  if(sum==n) 
      printf("%d ",n); 
  }
  return 0; 
} 
/* 
Sample output: 
Enter the minimum range: 1 
Enter the maximum range: 20 
Perfect numbers in given range is: 6 
*/

Example Code 3: from 1 to 100

#include<stdio.h> 
int main()
{ 
  int n,i,sum; 
  printf("Perfect numbers are: "); 
  for(n=1;n<=100;n++){ 
    i=1; 
    sum = 0; 
    while(i<n)
  { 
      if(n%i==0) 
           sum=sum+i; 
          i++; 
    } 
    if(sum==n) 
      printf("%d ",n); 
  }
  return 0; 
} 

/*
Output: 
Perfect numbers are: 6 28 
*/

Previous & Next


Please turn AdBlock off, and continue learning

Notice for AdBlock users

Please turn AdBlock off
Index

Discover more from ArunEworld

Subscribe now to keep reading and get access to the full archive.

Continue reading