Perfect Number in c Programming

28 Dec 2022 Balmiki Mandal 0 C Programming

Understanding Perfect Numbers in C

A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). In other words, it is a number that is half the sum of all of its positive divisors.

Properties of Perfect Numbers

  • Perfect numbers have fascinated mathematicians for centuries due to their intriguing properties.
  • They are relatively rare compared to other types of numbers.
  • The first few perfect numbers are 6, 28, 496, and 8128.

Calculating Perfect Numbers in C

1. Brute Force Method

  • The simplest way to find perfect numbers is through brute force.
  • Iterate through numbers, calculate their divisors, and check if they are perfect.
  • This method is not efficient for large numbers.

 

2. Euclid's Formula

  • A more efficient approach is using Euclid's formula for even perfect numbers.
  • It generates perfect numbers of the form 2�−1(2�−1), where 2�−1 is a Mersenne prime.
  • This method is faster and can handle larger perfect numbers.

Example Code in C

#include 

int isPerfect(int num) {
    int sum = 1;
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            sum += i;
            if (i * i != num) {
                sum += num / i;
            }
        }
    }
    return sum == num;
}

int main() {
    for (int i = 2; i <= 10000; i++) {
        if (isPerfect(i)) {
            printf("%d is a perfect number.\n", i);
        }
    }
    return 0;
}

 

Top Search


Related Program part -1

Prime number in c 

Armstrong Number in C 

Strong number in c

Perfect Number in c

palindrome number in c

Fibonacci series in c

Related Program part -2

Prime number in 1 to 100

Armstrong Number in 1 to 100

Strong number in 1 to 100

Perfect Number in 1 to 100

palindrome number in 1 to 100

Fibonacci series in  1 to 100

Conclusion

 

Understanding perfect numbers and implementing algorithms to find them in C can be a fascinating exercise in number theory and programming. Whether using a brute force method or a more sophisticated formula like Euclid's, exploring perfect numbers can be a rewarding endeavor for both beginners and experienced programmers.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.