Write a program to find the sum of cube of digits of a number.
For example,
Input 12345 Output 225 Explaination 13 + 23 + 33 + 43 + 53 = 225
Approach
The solution to this problem is very simple. We will simply using % ( MOD operator ) to read each digit of the input number one by one and store their sum in a temporary variable.
Steps
- Let N be the input number.
- Initialize a variable sum = 0.
- Repeat the following steps while N > 0.
- Set temp = N % 10. This stores the rightmost digit of N in temp.
- Set N = N / 10. This step removes the rightmost digit of N.
- Set sum = sum + temp * temp * temp.
- The sum of the cube of digits of the input number is stored in sum.
#include <stdio.h>
#include <math.h>
// returns sum of cube of digits of n
int sum_of_cube(int n) {
int sum = 0;
int temp;
while( n > 0 ){
temp = n % 10; // store rightmost digit of n in temp
n = n / 10; // remove rightmost digit of n
sum = sum + temp * temp * temp;
}
return sum;
}
int main() {
int n;
printf("Enter a Number: ");
scanf("%d", &n);
printf("Sum of the cube of digits of %d = %d", n, sum_of_cube(n));
}
Output
Enter a Number: 12341
Sum of the cube of digits of 12341 = 101
Read
Well written!