Sum of digits of a given number to a given power
Given a number, we need to find the sum of all the digits of a number which we get after raising the number to a specified power.
Input: number = 5, power = 4 Output: 13 Explanation: Raising 5 to the power 4 we get 625. Now adding all the digits = 6 + 2 + 5 Input: number = 9, power = 5 Output: 27 Explanation: Raising 9 to the power 5 we get 59049. Now adding all the digits = 5 + 9 + 0 + 4 + 9
The approach for Python is explained. we have used pow() function to calculate the base to the power value. Then we have extracted every digit as string using str() method. Since we can’t calculate the sum of strings, we converted every string digit back to integer using int() method. Finally, we used sum() function to get the sum of all the digits. This solution will look very simple in Python but it won’t be so short in other languages. After running both the codes, one can compare the time elapsed and the memory used in both the given language i.e., Python and Java.
Below is the implementation of above idea :
This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.