C program to find all perfect numbers between 1 to n

Write a C program to print all Perfect numbers between 1 to n. C program to find all perfect numbers between a given range. How to print all perfect numbers between a given interval using loop in C programming.

Example:
Input upper limit: 100
Output perfect numbers: 6, 28

Also view this program using functions - C program to print all perfect numbers between given interval using functions.

Required knowledge

Basic C programming, For loop, Nested loop, If else

Perfect number

A Perfect number is a positive integer which is equal to the sum of its proper positive divisors. For example: 6, 28 are the first two perfect numbers.

Before moving on to this program you must know how to check perfect numbers without which it would be difficult to get through this program.

Program to find all perfect numbers

/**
 * C program to print all Perfect numbers between 1 to n 
 */

#include <stdio.h>

int main()
{
    int i, j, n, sum = 0;

    /* Reads upper limit to print perfect numbers upto */
    printf("Enter any number to print perfect number up to: ");
    scanf("%d", &n);



    printf("\nAll Perfect numbers between 1 to %d:\n", n);

    
    /*
     * Iterates from 1 to n and print if it is perfect number
     */
    for(i=1; i<=n; i++)
    {
        sum = 0;

        /*
         * Checks whether the current number i is Perfect number or not
         */
        for(j=1; j<i; j++)
        {
            if(i%j==0)
            {
                sum += j;
            }
        }
 
        /* If the current number i is Perfect number */
        if(sum == i)
        {
            printf("%d is Perfect Number\n", i);
        }
    }

    return 0;
} 


Output
Enter any number to print perfect number upto: 100

All Perfect numbers between 1 to 100:
6 is Perfect Number
28 is Perfect Number

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment