Check if a Number is Perfect in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to write a C program to check if a given number is a perfect number. The program will read an integer input from the user, calculate the sum of its proper divisors, and then determine whether the number is perfect or not. The lab covers fundamental concepts in number theory and discrete mathematics, providing a practical application of these principles in C programming.

The program first prompts the user to enter a positive integer, then calculates the sum of the number's proper divisors (i.e., all positive integers less than the number that divide the number evenly). Finally, the program compares the sum of the proper divisors to the original number and prints the result, indicating whether the number is perfect or not.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435142{{"`Check if a Number is Perfect in C`"}} c/variables -.-> lab-435142{{"`Check if a Number is Perfect in C`"}} c/if_else -.-> lab-435142{{"`Check if a Number is Perfect in C`"}} c/for_loop -.-> lab-435142{{"`Check if a Number is Perfect in C`"}} c/user_input -.-> lab-435142{{"`Check if a Number is Perfect in C`"}} c/math_functions -.-> lab-435142{{"`Check if a Number is Perfect in C`"}} end

Read an Integer

In this step, you'll learn how to read an integer input in C for checking perfect numbers. We'll create a C program that allows users to input a number to be analyzed.

First, let's create a new C file in the project directory:

cd ~/project
nano perfect_number.c

Now, add the following code to the file:

#include <stdio.h>

int main() {
    int number;

    // Prompt user for input
    printf("Enter a positive integer to check if it's a perfect number: ");
    scanf("%d", &number);

    // Print the entered number to verify input
    printf("You entered: %d\n", number);

    return 0;
}

Example output:

Enter a positive integer to check if it's a perfect number: 28
You entered: 28

Let's break down the code:

  • #include <stdio.h> includes the standard input/output library
  • scanf("%d", &number) reads an integer input from the user
  • printf() is used to prompt for input and display the entered number

Compile and run the program:

gcc perfect_number.c -o perfect_number
./perfect_number

Sum Proper Divisors and Compare to Number

In this step, you'll modify the previous C program to calculate the sum of proper divisors and determine if the number is perfect.

Open the existing file and update the code:

nano ~/project/perfect_number.c

Replace the previous code with:

#include <stdio.h>

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

    // Prompt user for input
    printf("Enter a positive integer to check if it's a perfect number: ");
    scanf("%d", &number);

    // Calculate sum of proper divisors
    for (int i = 1; i < number; i++) {
        if (number % i == 0) {
            sum += i;
        }
    }

    // Check if 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;
}

Compile and run the program:

gcc perfect_number.c -o perfect_number
./perfect_number

Example output for a perfect number:

Enter a positive integer to check if it's a perfect number: 28
28 is a perfect number!

Example output for a non-perfect number:

Enter a positive integer to check if it's a perfect number: 12
12 is not a perfect number.

Key concepts explained:

  • The for loop iterates through numbers from 1 to number - 1
  • number % i == 0 checks if i is a divisor of the number
  • sum += i adds all proper divisors
  • A perfect number is a positive integer equal to the sum of its proper divisors

Print Result

In this final step, you'll enhance the program to provide more detailed output about the perfect number, including its divisors and sum.

Open the file and update the code:

nano ~/project/perfect_number.c

Replace the previous code with:

#include <stdio.h>

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

    // Prompt user for input
    printf("Enter a positive integer to check if it's a perfect number: ");
    scanf("%d", &number);

    // Print header for divisors
    printf("Proper divisors of %d: ", number);

    // Calculate sum of proper divisors and print them
    for (int i = 1; i < number; i++) {
        if (number % i == 0) {
            printf("%d ", i);
            sum += i;
        }
    }

    // Print detailed result
    printf("\n\nSum of proper divisors: %d", sum);

    // Check and print perfect number status
    if (sum == number) {
        printf("\n%d is a PERFECT NUMBER!\n", number);
    } else {
        printf("\n%d is NOT a perfect number.\n", number);
    }

    return 0;
}

Compile and run the program:

gcc perfect_number.c -o perfect_number
./perfect_number

Example output for a perfect number (28):

Enter a positive integer to check if it's a perfect number: 28
Proper divisors of 28: 1 2 4 7 14

Sum of proper divisors: 28
28 is a PERFECT NUMBER!

Example output for a non-perfect number (12):

Enter a positive integer to check if it's a perfect number: 12
Proper divisors of 12: 1 2 3 4 6

Sum of proper divisors: 16
12 is NOT a perfect number.

Key improvements:

  • Now prints all proper divisors
  • Shows the sum of proper divisors
  • Provides clear, formatted output
  • Maintains the core logic of perfect number detection

Summary

In this lab, you will learn how to read an integer input in C and determine whether a number is perfect. First, you will create a C program that prompts the user to enter a positive integer. Then, you will calculate the sum of the number's proper divisors and compare it to the original number to check if it is a perfect number. Finally, you will print the result to the console.

The key learning points from this lab are: reading integer input using scanf(), calculating the sum of proper divisors using a for loop, and comparing the sum to the original number to determine if it is a perfect number.

Other C Tutorials you may like