Sum of power of digits in python
View Discussion Show Improve Article Save Article View Discussion Improve Article Save Article 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. C++
Java
Python3
C#
PHP
Javascript
Output: 13 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 . See your article appearing on the GeeksforGeeks main page and help other Geeks. How do you sum all the digits in a number in Python?Using Sum() method
The sum() method is used to compute the sum of digits of a number in python in a list. Convert the number to a string using str(), then strip the string and convert it to a list of numbers with the strip() and map() methods, respectively. Then, compute the total using the sum() method.
How do you find the power of a number in Python?How to find the power of a number in Python. import math. print(math. pow(4,2)) Run. Importing math module in Python.. def power(n,e): res=0. for i in range(e): res *= n. return res. print(pow(4,2)) Run. ... . def power(n, e): if e == 0: return 1. elif e == 1: return n. else: return (n*power(n, e-1)). How do you find the power of 2 in Python?A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. ... . All power of two numbers have only one bit set.. How do you sum a 3 digit number in Python?Method-2: Using sum() methods.: The sum() method is used to sum of numbers in the list. Convert the number to string using str() and strip the string and convert to list of number using strip() and map() method resp. Then find the sum using the sum() method.
|