C PROGRAMMING PROGRAM • LOOPS & NUMBER PROBLEMS

Check Whether a Number Is Strong

Check whether an integer equals the sum of the factorials of its decimal digits.

IntermediateDigit factorialNested loopStrong number

PROBLEM UNDERSTANDING

Input and expected output

Sample input
145
Sample output
Strong number

COMPLETE C PROGRAM

Complete C implementation

strong-number.c
Open in compiler
#include <stdio.h>

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

    printf("Enter a non-negative integer: ");
    scanf("%d", &number);
    if (number < 0) {
        printf("Use a non-negative integer.\n");
        return 0;
    }
    value = number;
    do {
        int digit = value % 10;
        int factorial = 1;
        for (int item = 2; item <= digit; item++) factorial *= item;
        sum += factorial;
        value /= 10;
    } while (value > 0);
    printf(sum == number ? "Strong number\n" : "Not a strong number\n");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Strong number
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read a non-negative integer and keep its original value in number.
  2. Copy number into value so extracting digits does not destroy the original.
  3. Extract a digit with value % 10, calculate its factorial starting from 1, and add it to sum.
  4. Remove that digit using value /= 10 and repeat; the do-while also processes input 0.
  5. Compare sum with number and print the result.

For 145, the extracted digits are 5, 4 and 1. Their factorials are 120, 24 and 1, so the total is 145 and the number is strong. factorial is reset to 1 for every digit; this also handles 0! = 1 correctly. Input 0 produces a sum of 1 and is not strong. Negative inputs are rejected. With d decimal digits, each digit needs at most eight loop iterations, so the algorithm uses O(d) time and O(1) auxiliary space. This demonstration assumes scanf successfully reads an integer; production input handling should check its return value.

EFFICIENCY

Time and space complexity

Time complexity

O(d)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Reset factorial to 1 inside the digit loop, not once before processing all digits.

Check this

Compare sum with the preserved number, not value, which becomes 0 after extraction.

Check this

Do not replace the do-while with an unchecked while(value > 0): input 0 must still process its zero digit.

Try it yourself

Practice: Test 1, 2 and 145: all are strong. Test 0 and 123: neither is strong. Test -1: the program rejects it. Explain why the digit 0 contributes 1, not 0.