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

📅  最后修改于: 2021-04-18 02:33:50             🧑  作者: 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++
// 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)