Perfect Number Program In C

Published: 30 Dec 2024
Reading Time: 5 min read

Overview

A perfect number is a positive integer equal to the sum of its proper divisors without including itself. These numbers have a mathematical allure, and in this article, we go into the details of how to write a perfect numbers program in C.

Table of Contents

What is the Perfect Number Program in C

A perfect number is a positive integer, which is equal to the sum of proper divisors but excludes the number. For example, 28 has divisors 1, 2, 4, 7, and 14. Adding these divisors gives 1 + 2 + 4 + 7 + 14 = 28, which matches the original number, hence it's a perfect number.

A C program can easily decide on the perfect nature of a specific number due to the use of loops and conditional statements.

Three Methods to Find Perfect Numbers in C

You can find the perfect number in C using three different methods:

1. Using for Loop

The for loop iterates through all integers that are less than the number you have entered. It checks if each number is a divisor by using the modulus operator (%). If it is divisible, the divisor is added to a sum variable. Once the loop ends, the sum is compared to the original number to determine if it is perfect.

2. Using while Loop

A while loop can also be used to perform the same operation as the for loop. But it provides more flexibility in defining conditions. The loop continues as long as the condition (e.g., a counter variable being less than the number) is true. Then, it checks divisors and updates the sum.

3. Using Recursion in C

Recursion involves a function calling itself to calculate the sum of divisors. It starts with the smallest divisor, and the function checks the divisibility. Then it adds the divisor to a sum and calls itself with the next number. It stops when all potential divisors are checked and returns the sum to determine if the number is perfect.

C Program to Find Perfect Number Using for Loop

Here's a program in C to check whether a given number is perfect or not.

Important Components and Operators

1. for Loop: Iterates through numbers less than the given number to check for divisors.

2. % (Modulus Operator): Determines if a number is a divisor by checking if the remainder is zero (a % b == 0).

3. += (Addition Assignment Operator): Adds the divisor to the sum variable (sum += b).

4. if Statement: Compares the sum of divisors to the original number to check if it's a perfect number (if (sum == a)).

5. printf(): Outputs the perfect number to the console.

6. Variables:

Code Example

#include <stdio.h>

int main() {
    // declaring and initialising variables
    int number, remainder, sum = 0, j;

    // taking input from the user
    printf("Enter a number: ");
    scanf("%d", &number);

    // finding all divisors and adding them
    for (j = 1; j < number; j++) {
        remainder = number % j;
        if (remainder == 0) {
            sum = sum + j;
        }
    }

    // checking if the number is perfect
    if (sum == number)
        printf("%d is a Perfect Number.\n", number);
    else
        printf("%d is not a Perfect Number.\n", number);

    return 0; // indicates successful program termination
}

Output Examples

Enter a number: 6
6 is a Perfect Number.

=== Code Execution Successful ===
Enter a number: 100
100 is not a Perfect Number.

=== Code Execution Successful ===

Program Explanation

Complexity Analysis

Time Complexity: O(n^2), where n is the range of numbers being checked.

Space Complexity: O(1) as the program uses a fixed amount of memory.

Perfect Number Program in C Using while Loop

Now let's take a look at how the perfect number can be found using a while loop.

Important Components and Operators

1. while Loop: Iterates through potential divisors until the condition (i < number) is false.

2. % (Modulus Operator): Determines if a number is a divisor by checking if the remainder is zero (number % i == 0).

3. += (Addition Assignment Operator): Adds the divisor to the sum variable (sum += i).

4. if Statement: Compares the sum of divisors to the original number to determine if it is perfect (if (sum == number)).

5. printf(): Prints whether the number is perfect or not.

6. Variables:

Code Example

#include <stdio.h>

int main() {
    int i = 1, number, sum = 0;

    // Prompt user for input
    printf("Enter any number to check if it is a Perfect Number: ");
    scanf("%d", &number);

    // Loop to find all divisors and calculate their sum
    while (i < number) {
        if (number % i == 0) {
            sum = sum + i;
        }
        i++;
    }

    // Check if the number is perfect
    if (sum == number)
        printf("%d is a Perfect Number.\n", number);
    else
        printf("%d is not a Perfect Number.\n", number);

    return 0; // Indicates successful program termination
}

Output Example

Enter any number to check if it is a Perfect Number: 6
6 is a Perfect Number.

=== Code Execution Successful ===

Program Explanation

The program checks if a number is perfect by summing all its proper divisors using a while loop. It iterates from 1 to the number minus 1, adding divisors to the sum. After the loop, it compares the sum with the input number and prints whether it's a perfect number or not.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Perfect Number Program in C Using Recursion

Here's an example using recursion. The program recursively calculates the sum of its divisors. It starts with b = 1 and checks divisibility until b equals the number. If the sum of divisors equals the input number, it's printed as a perfect number; otherwise, it's not.

Important Components and Operators

1. Recursion: The program uses a recursive function to repeatedly check divisors and calculate the sum of proper divisors.

2. % (Modulus Operator): Checks if the current value (n % b) is a divisor by verifying the remainder is zero.

3. += (Addition Assignment Operator): Adds the divisor to the sum variable when the condition (n % b == 0) is satisfied.

4. if and else if Statements:

5. Variables:

Code Example

#include <stdio.h>

// Recursive function to calculate the sum of divisors
int PerfectNum(int n, int sum, int b) {
    if (b < n) {
        if (n % b == 0) {
            sum += b;  // Add divisor to sum
        }
        return PerfectNum(n, sum, b + 1); // Recursive call
    }
    return sum;  // When b equals n, return the sum of divisors
}

int main() {
    int n;
    printf("Enter a number:\n");
    scanf("%d", &n);
    // Initialize sum to 0 and start the recursion with b=1
    int sum = PerfectNum(n, 0, 1);

    // Check if the sum of divisors equals the number
    if (sum == n) {
        printf("\n%d is a perfect number.\n", n);
    } else {
        printf("\n%d is not a perfect number.\n", n);
    }

    return 0;  // Indicate successful termination
}

Output Example

Enter a number:
6

6 is a perfect number.

=== Code Execution Successful ===

Program Explanation

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

C Program to Find Perfect Numbers From 1 to 100

The program checks each number from 1 to 100 by calculating the sum of its divisors. For each number, it iterates through all smaller numbers and adds the divisors. If the sum equals the number, it is printed as a perfect number.

Code Example

#include <stdio.h>

int main() {
    int a, b, sum;

    printf("Perfect numbers between 1 and 100 are:\n");

    // Iterate from 1 to 100
    for (a = 1; a <= 100; a++) {
        sum = 0;

        // Check whether the current number is perfect or not
        for (b = 1; b < a; b++) {
            if (a % b == 0) {
                sum += b;  // Add divisor to sum
            }
        }

        // If the sum of divisors equals the number itself, it's a perfect number
        if (sum == a) {
            printf("%d ", a);
        }
    }

    return 0;
}

Output Example

Perfect numbers between 1 and 100 are:
6 28

=== Code Execution Successful ===

C Program for Perfect Numbers Between 1 and 1000

Here's the code for a program that displays all perfect numbers from 1 to 1000. The program iterates through each number from 1 to 1000 and calculates the sum of its divisors. If the sum of divisors equals the number itself, the program prints the number as a perfect number. Perfect numbers like 6, 28 and 496 are displayed.

Code Example

#include <stdio.h>

int main()
{
    int a, b, sum;
    int end=1000;

    printf("All Perfect numbers between 1 to 1000");

    /* Iterate from 1 to 1000*/
    for(a=1; a<=end; a++)
    {
        sum = 0;

        /* Check whether the current number is the Perfect number or not */
        for(b=1; b<a; b++)
        {
            if(a % b == 0)
            {
                sum += b;
            }
        }
        if(sum == a)
        {
            printf("%d, ", a);
        }
    }

    return 0;
}

Output Example

Perfect numbers between 1 and 100 are:
6 28

=== Code Execution Successful ===

Conclusion

Basic programming knowledge, such as the usage of loops, conditions, and divisor calculations, is essential to learn in this program. It contributes to developing problem-solving skills necessary for further work on other, more complicated code-based issues. When learned well, such concepts strengthen analytical skills, which play an essential foundation for constant evolution as a software developer. To become job ready consider enrolling into the CCBP 4.0 Academy program and becoming a skilled software developer.

Frequently Asked Questions

1. What is a perfect number?

A perfect number is a positive integer equal to the sum of its proper divisors, excluding itself. For example, 6 is perfect because 1 + 2 + 3 = 6.

2. How does the C program find perfect numbers?

The program iterates through numbers and calculates the sum of their divisors. If the sum equals the number, it is considered perfect and printed.

3. Why is learning about perfect numbers important in coding?

Learning about perfect numbers enhances understanding of loops, conditionals, and algorithm design. It improves problem-solving skills essential for more complex coding challenges.

4. Can the program find perfect numbers for a range beyond 100?

Yes, the program can be modified to find perfect numbers within any desired range by adjusting the loop conditions.

5. How can the logic of this program be applied in real-world scenarios?

The logic of finding divisors and optimising calculations can be applied to algorithms in number theory, cryptography, and optimisation problems.


Related Articles


Source: NxtWave - CCBP 4.0 Academy
Original URL: https://www.ccbp.in/blog/articles/perfect-number-program-in-c