Value required to be added to N to obtain the sum of first M multiples of K
Last Updated :
06 Dec, 2022
Given three positive integers N, K, and M, the task is to find the number to be added to N to obtain the sum of first M multiples of K.
Examples:
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 multiple of 2 is 2.
The value to be added to 5 to get 2 is (2 – 5) = -3
Approach: Follow the steps below to solve the problem:
- Calculate the sum of first M multiples of K, which will be equal to K * (1 + 2 + 3 + … M) = K * M * (M + 1) / 2.
- Initialize a variable, say res, to store the number required to be added to N to obtain sum.
- Therefore, res will be equal to sum – N. Print the value of res.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
static int printNumber( int N, int K, int M)
{
int sum = K * (M * (M + 1) / 2);
return sum - N;
}
int main()
{
int N = 17;
int K = 3;
int M = 4;
cout << printNumber(N, K, M);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int printNumber( int N, int K, int M)
{
int sum = K * (M * (M + 1 ) / 2 );
return sum - N;
}
public static void main(String[] args)
{
int N = 17 ;
int K = 3 ;
int M = 4 ;
System.out.print(printNumber(N, K, M));
}
}
|
Python3
def printNumber(N, K, M):
sum = K * (M * (M + 1 ) / 2 )
return sum - N
N = 17
K = 3
M = 4
print ( int (printNumber(N, K, M)))
|
C#
using System;
class GFG
{
static int printNumber( int N, int K, int M)
{
int sum = K * (M * (M + 1) / 2);
return sum - N;
}
public static void Main(String[] args)
{
int N = 17;
int K = 3;
int M = 4;
Console.Write(printNumber(N, K, M));
}
}
|
Javascript
<script>
function printNumber(N, K, M)
{
var sum = K * ((M * (M + 1)) / 2);
return sum - N;
}
var N = 17;
var K = 3;
var M = 4;
document.write(printNumber(N, K, M));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...