📜  求 N 次操作的功率和 LCM 的乘积之和

📅  最后修改于: 2022-05-13 01:56:08.998000             🧑  作者: Mango

求 N 次操作的功率和 LCM 的乘积之和

给定一个整数N ,任务是在i最初为1时执行以下N操作后找到该值:

  • i的值的(N – i)次幂,然后将其乘以i 和 N 的 lcm
  • 将此值添加到最终答案中。
  • i增加1

例子:

方法:这是一个简单的基于实现的问题。我们的想法是如前所述逐个执行步骤并找到最终总和。请按照以下步骤解决问题:

  • i = 1开始遍历iN
    • 计算iN的 LCM。
    • 计算iNi次方的值。
    • 继续将上述两步的值相乘,并将其添加到最终总和(最初总和将为 0)。
  • 返回总和

下面是上述方法的实现:

C++
// C++ program to implement the approach
 
#include 
using namespace std;
 
// GCD function
int gcd(int x, int y)
{
    if (x == 0)
        return y;
    return gcd(y % x, x);
}
 
// Function to find sum
int findsum(int N)
{
    int i, hcf, sum = 0, lcm;
 
    for (i = 1; i <= N; i++) {
 
        // Returning the gcd of two numbers
        hcf = gcd(i, N);
 
        // Calculating lcm using lcm*hcf=
        // value1*value2.
        lcm = (i * N) / hcf;
        sum += pow(i, N - i) * lcm;
    }
    return sum;
}
 
// Driver function
int main()
{
    int N = 5;
 
    // Function call
    cout << findsum(N) << endl;
    return 0;
}


Java
// Java program to implement the approach
import java.io.*;
 
class GFG
{
 
  // GCD function
  public static int gcd(int x, int y)
  {
    if (x == 0)
      return y;
    return gcd(y % x, x);
  }
 
  // Function to find sum
  public static int findsum(int N)
  {
    int i = 0, hcf = 0, sum = 0, lcm = 0;
 
    for (i = 1; i <= N; i++) {
 
      // Returning the gcd of two numbers
      hcf = gcd(i, N);
 
      // Calculating lcm using lcm*hcf=
      // value1*value2.
      lcm = (i * N) / hcf;
      sum += Math.pow(i, N - i) * lcm;
    }
    return sum;
  }
  public static void main(String[] args)
  {
    int N = 5;
 
    // Function call
    System.out.println(findsum(N));
  }
}
 
// This code is contributed by Rohit Pradhan


C#
// C# program to implement the approach
using System;
 
public class GFG{
 
  // GCD function
  public static int gcd(int x, int y)
  {
    if (x == 0)
      return y;
    return gcd(y % x, x);
  }
 
  // Function to find sum
  public static int findsum(int N)
  {
    int i = 0, hcf = 0, sum = 0, lcm = 0;
 
    for (i = 1; i <= N; i++) {
 
      // Returning the gcd of two numbers
      hcf = gcd(i, N);
 
      // Calculating lcm using lcm*hcf=
      // value1*value2.
      lcm = (i * N) / hcf;
      sum += (int)Math.Pow(i, N - i) * (int)lcm;
    }
    return sum;
  }
 
  // Driver Code
  static public void Main ()
  {
    int N = 5;
 
    // Function call
    Console.Write(findsum(N));
  }
}
 
// This code is contributed by hrithikgarg03188.


输出
305

时间复杂度: O(N * log N)
辅助空间: O(1)