C program to print all strong numbers between 1 to n

Write a C program to print all Strong numbers between 1 to n. C program to generate all strong numbers between a given range. How to print all strong numbers between given interval using loop in C programming.

Example:
Input upper limit: 1000
Output strong numbers: 1, 2, 145

Also if you are interested check this program using another method - C program to print all strong numbers between given range using functions.

Required knowledge

Basic C programming, If else, For loop

Strong number

Strong numbers are the numbers whose sum of factorial of digits is equal to the number. For Example: 145 is a strong number
Since 1! + 4! + 5! = 145

Before we print all Strong numbers between 1 to n, we must know how to check Strong number in C.

Program to print strong numbers

/**
 * C program to print all Strong Numbers between 1 to n
 */

#include <stdio.h>

int main()
{
    int i, j, cur, n;
    long fact, sum;

    /* Reads a number from user */
    printf("Find Strong numbers between 1 to ");
    scanf("%d", &n);



    printf("All Strong numbers between 1 to %d are:\n", n);
    
    /* Finds all Strong numbers between 1 to n */
    for(i=1; i<=n; i++)
    {
        /* Number to check whether it is Strong number or not */
        cur = i;

        sum = 0;

        /*
         * Finds the sum of factorial of each digits
         */ 
        while(cur!=0)
        {
            fact = 1;
            
            /* Computes factorial of last digit i.e. cur%10 */
            for( j=1; j<=cur%10; j++)
            {
                fact = fact * j;
            }

            sum = sum + fact; 

            cur = cur / 10;
        }
        
        /*
         * Checks if it is Strong number then print it
         */  
        if(sum==i)
        {
            printf("%d is Strong number\n", i);
        }
    }

    return 0;
}


Output
Find Strong numbers between 1 to 100000
All Strong numbers between 1 to 100000 are:
1 is Strong number
2 is Strong number
145 is Strong number
40585 is Strong 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