Program to find value of 1^k + 2^k + 3^k + … + n^k
Last Updated :
15 Nov, 2022
Given two positive integers N and K. The task is to evaluate the value of 1K + 2 K + 3K + … + NK.
Examples:
Input: N = 3, K = 4
Output: 98
Explanation:
?(x4) = 14 + 24 + 34, where 1 ? x ? N
?(x4) = 1 + 16 + 81
?(x4) = 98
Input: N = 8, K = 4
Output: 8772
Approach:
- The idea is to find the value of xK using pow() function. (where x is from 1 to N).
- The required sum is the summation of all values calculated above.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findSum( int N, int k)
{
int sum = 0;
for ( int i = 1; i <= N; i++) {
sum += pow (i, k);
}
return sum;
}
int main()
{
int N = 8, k = 4;
cout << findSum(N, k) << endl;
return 0;
}
|
Java
class GFG {
static int findSum( int N, int k)
{
int sum = 0 ;
for ( int i = 1 ; i <= N; i++) {
sum += ( int )Math.pow(i, k);
}
return sum;
}
public static void main (String[] args)
{
int N = 8 , k = 4 ;
System.out.println(findSum(N, k));
}
}
|
Python 3
from math import pow
def findSum(N, k):
sum = 0
for i in range ( 1 , N + 1 , 1 ):
sum + = pow (i, k)
return sum
if __name__ = = '__main__' :
N = 8
k = 4
print ( int (findSum(N, k)))
|
C#
using System;
public class GFG {
static int findSum( int N, int k)
{
int sum = 0;
for ( int i = 1; i <= N; i++) {
sum += ( int )Math.Pow(i, k);
}
return sum;
}
public static void Main ( string [] args)
{
int N = 8, k = 4;
Console.WriteLine(findSum(N, k));
}
}
|
Javascript
<script>
function findSum(N, k)
{
let sum = 0;
for (let i = 1; i <= N; i++) {
sum += Math.pow(i, k);
}
return sum;
}
let N = 8, k = 4;
document.write(findSum(N, k));
</script>
|
Time Complexity: O(N * log(k)) (here we iterate for loop from i = 1 to N and we need to calculate pow (i,k) which required log(k) time so overall time complexity will be O(N * log(k)) )
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...