📜  需要添加到 N 以获得 K 的前 M 个倍数的总和的值

📅  最后修改于: 2021-10-26 05:58:07             🧑  作者: Mango

给定三个正整数NKM ,任务是找到要与N相加的数以获得K的前M倍数之和。

例子:

处理方法:按照以下步骤解决问题:

  1. 计算K的前M 个倍数的总和,这将等于K * (1 + 2 + 3 + … M) = K * M * (M + 1) / 2
  2. 初始化一个变量,比如res ,以存储需要添加到N以获得sum 的数字
  3. 因此, res将等于sum – N 。打印res的值。

下面是上述方法的实现:

C++
// C++ 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


Javascript


输出
13

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