给定三个正整数N , K和M ,任务是找到要添加到N的数字,以获得K的前M倍的总和。
例子:
Input: N = 17, K = 3, M = 4
Output: 13
Explanation:
Sum of first 4 multiples of 3 = (3 + 6 + 9 + 12) = 30.
Therefore, the value to be added to 17 is (30 – 17) = 13.
Therefore, the required output is 13.
Input: N = 5, K = 2, M = 1
Output: -3
Explanation:
Sum of first 1 multiples of 2 is 2.
The value to be added to 5 to get 2 is (2 – 5) = -3
方法:请按照以下步骤解决问题:
- 计算K的前M倍的总和,等于K *(1 + 2 + 3 +…M) = K * M *(M +1)/ 2 。
- 初始化一个变量,例如res ,存储要加到N以获得sum所需的数字。
- 因此, res将等于sum – N。重视res的价值。
下面是上述方法的实现:
C++
// Python3 program for the above approach
#include
using namespace std;
// Function to print the value
// to be added to N to obtain
// sum of first M multiples of K
static int printNumber(int N, int K, int M)
{
// Store the sum of the
// first M multiples of K
int sum = K * (M * (M + 1) / 2);
// Store the value to be
// added to obtain N
return sum - N;
}
// Driver Code
int main()
{
// Input
int N = 17;
int K = 3;
int M = 4;
cout << printNumber(N, K, M);
return 0;
}
// This code is contributed by shubhamsingh10
Java
// Java code of above approach
import java.util.*;
class GFG
{
// Function to print the value
// to be added to N to obtain
// sum of first M multiples of K
static int printNumber(int N, int K, int M)
{
// Store the sum of the
// first M multiples of K
int sum = K * (M * (M + 1) / 2);
// Store the value to be
// added to obtain N
return sum - N;
}
// Driver code
public static void main(String[] args)
{
// Input
int N = 17;
int K = 3;
int M = 4;
System.out.print(printNumber(N, K, M));
}
}
// This code is contributed by offbeat
Python3
# Python3 program for the above approach
# Function to print the value
# to be added to N to obtain
# sum of first M multiples of K
def printNumber(N, K, M):
# Store the sum of the
# first M multiples of K
sum = K * (M * (M + 1) / 2)
# Store the value to be
# added to obtain N
return sum - N
# Driver Code
# Input
N = 17
K = 3
M = 4
print(int(printNumber(N, K, M)))
C#
// C# program for the above approach
using System;
class GFG
{
// Function to print the value
// to be added to N to obtain
// sum of first M multiples of K
static int printNumber(int N, int K, int M)
{
// Store the sum of the
// first M multiples of K
int sum = K * (M * (M + 1) / 2);
// Store the value to be
// added to obtain N
return sum - N;
}
// Driver code
public static void Main(String[] args)
{
// Input
int N = 17;
int K = 3;
int M = 4;
Console.Write(printNumber(N, K, M));
}
}
// This code is contributed by shubhamsingh10
输出
13
时间复杂度: O(1)
辅助空间: O(1)