Divide a big number into two parts that differ by k in C++ Program

C++Server Side ProgrammingProgramming

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.


n = 100
k = 30


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


That's it. We have n and k. And there is nothing more in it. Let's see the code

 Live Demo

#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);


If you run the above code, then you will get the following result.

33 21


If you have any queries in the tutorial, mention them in the comment section.

Published on 27-Jan-2021 12:45:03