Sum of digits of a given number to a given power
Last Updated :
17 Feb, 2023
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.
Examples:
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 :
C++
#include<bits/stdc++.h>
using namespace std;
int calculate( int n, int power)
{
int sum = 0;
int bp = ( int ) pow (n, power);
while (bp != 0) {
int d = bp % 10;
sum += d;
bp /= 10;
}
return sum;
}
int main()
{
int n = 5;
int power = 4;
cout << calculate(n, power);
}
|
Java
public class base_power {
static int calculate( int n, int power)
{
int sum = 0 ;
int bp = ( int )Math.pow(n, power);
while (bp != 0 ) {
int d = bp % 10 ;
sum += d;
bp /= 10 ;
}
return sum;
}
public static void main(String[] args)
{
int n = 5 ;
int power = 4 ;
System.out.println(calculate(n, power));
}
}
|
Python3
def calculate(n, power):
return sum ([ int (i) for i in str ( pow (n, power))])
n = 5
power = 4
print (calculate(n, power))
|
C#
using System;
public class base_power
{
static int calculate( int n, int power)
{
int sum = 0;
int bp = ( int )Math.Pow(n, power);
while (bp != 0)
{
int d = bp % 10;
sum += d;
bp /= 10;
}
return sum;
}
public static void Main()
{
int n = 5;
int power = 4;
Console.WriteLine(calculate(n, power));
}
}
|
PHP
<?php
function calculate( $n , $power )
{
$sum = 0;
$bp = (int)pow( $n , $power );
while ( $bp != 0)
{
$d = $bp % 10;
$sum += $d ;
$bp /= 10;
}
return $sum ;
}
$n = 5;
$power = 4;
echo (calculate( $n , $power ));
?>
|
Javascript
<script>
function calculate( n, power)
{
sum = 0;
bp = Math.pow(n, power);
while (bp != 0) {
d = bp % 10;
sum =sum+ d;
bp = Math.floor(bp/ 10);
}
return sum;
}
n = 5;
power = 4;
document.write(calculate(n, power));
</script>
|
Output:
13
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...