Compute Sum of Each Digit Raised to Power of Digits Count
In this step, we will modify our previous program to calculate the sum of each digit raised to the power of the total number of digits.
Open the armstrong.c file:
cd ~/project
nano armstrong.c
Update the code to compute the digit sum:
#include <stdio.h>
#include <math.h>
int main() {
int number, originalNumber, remainder, digitCount = 0;
long long digitSum = 0;
// Prompt the user to enter a number
printf("Enter a number to check if it's an Armstrong number: ");
scanf("%d", &number);
// Store the original number for later comparison
originalNumber = number;
// Count the number of digits
while (number != 0) {
number /= 10;
digitCount++;
}
// Reset number to original value
number = originalNumber;
// Compute sum of each digit raised to power of digit count
while (number != 0) {
remainder = number % 10;
digitSum += pow(remainder, digitCount);
number /= 10;
}
// Print the results
printf("Number of digits: %d\n", digitCount);
printf("Sum of digits raised to power: %lld\n", digitSum);
return 0;
}
Compile the program with math library:
gcc armstrong.c -o armstrong -lm
./armstrong
Example output:
Enter a number to check if it's an Armstrong number: 153
Number of digits: 3
Sum of digits raised to power: 153
Key concepts explained:
digitCount
tracks the number of digits
pow(remainder, digitCount)
raises each digit to the power of total digit count
number % 10
extracts the last digit
number /= 10
removes the last digit in each iteration
long long
used to handle potentially large digit sums