C Program to Find Strong Number with Output and Explanation
if (sum == num) printf("Strong number");.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int factorial(int n) { int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; } return fact; } int main() { int num, temp, digit, sum = 0; printf("Enter a number: "); scanf("%d", &num); temp = num; if (temp == 0) { sum = factorial(0); } while (temp > 0) { digit = temp % 10; sum += factorial(digit); temp /= 10; } if (sum == num) printf("%d is a Strong number\n", num); else printf("%d is not a Strong number\n", num); return 0; }
Dry Run
Let's trace the number 145 through the code
Input number
num = 145, temp = 145, sum = 0
Extract digit and calculate factorial
digit = 5, factorial(5) = 120, sum = 0 + 120 = 120
Next digit
temp = 14, digit = 4, factorial(4) = 24, sum = 120 + 24 = 144
Next digit
temp = 1, digit = 1, factorial(1) = 1, sum = 144 + 1 = 145
Compare sum with original
sum = 145, num = 145, sum == num is true
| Digit | Factorial | Sum |
|---|---|---|
| 5 | 120 | 120 |
| 4 | 24 | 144 |
| 1 | 1 | 145 |
Why This Works
Step 1: Calculate factorial of digits
Each digit's factorial is calculated using a loop multiplying numbers from 1 to the digit.
Step 2: Sum factorials
Sum all factorials of digits extracted from the number.
Step 3: Compare sum with original number
If the sum equals the original number, it is a strong number.
Alternative Approaches
#include <stdio.h> int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } int main() { int num, temp, digit, sum = 0; printf("Enter a number: "); scanf("%d", &num); temp = num; if (temp == 0) { sum = factorial(0); } while (temp > 0) { digit = temp % 10; sum += factorial(digit); temp /= 10; } if (sum == num) printf("%d is a Strong number\n", num); else printf("%d is not a Strong number\n", num); return 0; }
#include <stdio.h> int main() { int fact[10] = {1,1,2,6,24,120,720,5040,40320,362880}; int num, temp, digit, sum = 0; printf("Enter a number: "); scanf("%d", &num); temp = num; if (temp == 0) { sum = fact[0]; } while (temp > 0) { digit = temp % 10; sum += fact[digit]; temp /= 10; } if (sum == num) printf("%d is a Strong number\n", num); else printf("%d is not a Strong number\n", num); return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The program loops through each digit once, so time depends on the number of digits d, making it O(d).
Space Complexity
Uses a fixed amount of extra space for variables and factorial calculation, so O(1).
Which Approach is Fastest?
Precomputing factorials in an array is fastest because it avoids repeated factorial calculations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative factorial | O(d * k) | O(1) | Simple and clear for small inputs |
| Recursive factorial | O(d * k) | O(k) due to recursion stack | Elegant but less efficient |
| Precomputed factorial array | O(d) | O(1) | Fastest for repeated checks |