Problem statement: Given a number, we need to find the sum of all the digits of the number that we get after raising the number to a specified power.
For example, 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
The first line contains the integer T, which stands for the number of test cases. The next T lines will contain the integer N.
1 <= T <= 100
1 <= T <= 104
Print the values corresponding to each test case.
The problem can be solved quite quickly with Python as it allows arbitrary large integers:
However, that wasn’t really challenging.
So, let’s figure out how we can solve the problem without the power of Python. Since every normal built-in data type can’t store such a large number, an array must hold the digits that we can sum over. How large does the array have to be? With Problem 25, I’ve proven the length L(n)
of number n.
You can probably compute the direct value of 21000. For example, in Python, you can obtain a value of (2**1000) and convert it to a string. In Java, you can use Big Integer to compute the value of two to the power of 1000.
We can use an array, or hash map, to store the digits of any big number. Every time we multiply each position (the values) of the array/hash map by two, we need to start from the ‘One’ position to carry over the digits.
With this mechanism, we can multiply 1000 times 2 quite quickly. We don’t even need 1000 arrays – one array is enough when we sum the result directly.
When implemented, the solution will be:
def power(n):power = 2for x in range(1, n):power = 2*powerreturn powerdef sum(n):pow = power(n)sum = 0while pow > 0:modulo = pow%10sum = sum + modulopow = int((pow - modulo)/10)return sumdef main():print(int(sum(1000)))if __name__ == '__main__':main()
This is an other way we can do the above program :
def Power_digit_sum(n):number = list(str(2**n))result= [int(i) for i in number]return sum(result)print(Power_digit_sum(15))print(Power_digit_sum(1000))