📜  程序查找1 ^ k + 2 ^ k + 3 ^ k +…+ n ^ k的值

📅  最后修改于: 2021-04-22 07:56:09             🧑  作者: Mango

给定两个正整数NK。任务是评估1 K + 2 K + 3 K +…+ N K的值

例子

方法:

  1. 这个想法是使用pow()函数找到x K的值。 (其中x从1到N)。
  2. 所需的总和是上面计算出的所有值的总和。

下面是上述方法的实现:

C++
// C++ Program to find the value
// 1^K + 2^K + 3^K + .. + N^K
#include 
using namespace std;
  
// Function to find value of
// 1^K + 2^K + 3^K + .. + N^K
int findSum(int N, int k)
{
    // Initialise sum to 0
    int sum = 0;
    for (int i = 1; i <= N; i++) {
  
        // Find the value of
        // pow(i, 4) and then
        // add it to the sum
        sum += pow(i, k);
    }
  
    // Return the sum
    return sum;
}
  
// Drivers Code
int main()
{
    int N = 8, k = 4;
  
    // Function call to
    // find the sum
    cout << findSum(N, k) << endl;
    return 0;
}


Java
// Java Program to find the value
// 1^K + 2^K + 3^K + .. + N^K
class GFG {
      
    // Function to find value of
    // 1^K + 2^K + 3^K + .. + N^K
    static int findSum(int N, int k)
    {
        // Initialise sum to 0
        int sum = 0;
        for (int i = 1; i <= N; i++) {
      
            // Find the value of
            // pow(i, 4) and then
            // add it to the sum
            sum += (int)Math.pow(i, k);
        }
      
        // Return the sum
        return sum;
    }
      
    // Drivers Code
    public static void main (String[] args) 
    {
        int N = 8, k = 4;
      
        // Function call to
        // find the sum
        System.out.println(findSum(N, k));
    }
}
  
// This code is contributed by AnkitRai01


C#
// C# Program to find the value
// 1^K + 2^K + 3^K + .. + N^K
  
using System;
  
public class GFG {
      
    // Function to find value of
    // 1^K + 2^K + 3^K + .. + N^K
    static int findSum(int N, int k)
    {
        // Initialise sum to 0
        int sum = 0;
        for (int i = 1; i <= N; i++) {
      
            // Find the value of
            // pow(i, 4) and then
            // add it to the sum
            sum += (int)Math.Pow(i, k);
        }
      
        // Return the sum
        return sum;
    }
      
    // Drivers Code
    public static void Main (string[] args) 
    {
        int N = 8, k = 4;
      
        // Function call to
        // find the sum
        Console.WriteLine(findSum(N, k));
    }
  
}
  
// This code is contributed by AnkitRai01


Python 3
# Python 3 Program to find the value
# 1^K + 2^K + 3^K + .. + N^K
from math import pow
  
# Function to find value of
# 1^K + 2^K + 3^K + .. + N^K
def findSum(N, k):
      
    # Initialise sum to 0
    sum = 0
    for i in range(1, N + 1, 1):
          
        # Find the value of
        # pow(i, 4) and then
        # add it to the sum
        sum += pow(i, k)
  
    # Return the sum
    return sum
  
# Drives Code
if __name__ == '__main__':
    N = 8
    k = 4
  
    # Function call to
    # find the sum
    print(int(findSum(N, k)))
  
# This code is contributed by Surendra_Gangwar


输出:
8772

时间复杂度: O(N)