求 N 次操作的功率和 LCM 的乘积之和
给定一个整数N ,任务是在i最初为1时执行以下N操作后找到该值:
- 求i的值的(N – i)次幂,然后将其乘以i 和 N 的 lcm 。
- 将此值添加到最终答案中。
- 将i增加1 。
例子:
Input: 5
Output: 305
Explanation: Following are the steps of the operations:
pow(1, 5-1) * (lcm(1, 5)) = 1 * 5
pow(2, 5-2) * (lcm(2, 5)) = 8 * 10 = 80
pow(3, 5-3) * (lcm(3, 5)) = 9 * 15 = 135
pow(4, 5-4) * (lcm(4, 5)) = 4 * 20 = 80
pow(5, 5-5) * (lcm(5, 5)) = 1 * 5 = 5
Hence the final sum is: 5 + 80 + 135 + 80 + 5 = 305
Input: 6
Output: 612
方法:这是一个简单的基于实现的问题。我们的想法是如前所述逐个执行步骤并找到最终总和。请按照以下步骤解决问题:
- 从i = 1开始遍历i到N
- 计算i和N的 LCM。
- 计算i的Ni次方的值。
- 继续将上述两步的值相乘,并将其添加到最终总和(最初总和将为 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)