In this tutorial, we are going to write a program that divides a number into two parts with a difference of k.
Let's see an example.
Input
n = 100 k = 30
Output
65 35
Here, we need to understand a little bit of math before diving into the problem. Let's see it.
We have a + b = n and a - b = k. By adding the two equations, we get
a = (n + k)/2 b = n - a
Example
That's it. We have n and k. And there is nothing more in it. Let's see the code
#include <bits/stdc++.h>
using namespace std;
void divideTheNumber(int n, int k) {
double a = (n + k) / 2;
double b = n - a;
cout << a << " " << b << endl;
}
int main() {
int n = 54, k = 12;
divideTheNumber(n, k);
}Output
If you run the above code, then you will get the following result.
33 21
Conclusion
If you have any queries in the tutorial, mention them in the comment section.