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.
PROBLEM UNDERSTANDING
Input and expected output
145
Strong number
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Strong number
PROGRAM EXPLANATION
Algorithm and explanation
- Read a non-negative integer and keep its original value in number.
- Copy number into value so extracting digits does not destroy the original.
- Extract a digit with value % 10, calculate its factorial starting from 1, and add it to sum.
- Remove that digit using value /= 10 and repeat; the do-while also processes input 0.
- 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
O(d)
O(1)
DEBUGGING CHECKLIST
Common mistakes
Reset factorial to 1 inside the digit loop, not once before processing all digits.
Compare sum with the preserved number, not value, which becomes 0 after extraction.
Do not replace the do-while with an unchecked while(value > 0): input 0 must still process its zero digit.
