C++ code to find who cannot give sufficient candies

C++Server Side ProgrammingProgramming

Suppose we have two numbers a and b. There are a and b number of candies in Amal's and Bimal's hand. Amal offered 1 candy to Bimal and Bimal gave two candies to Amal, in the next turn Amal gave 3 candies and Bimal gave 4 and so on. This continued until the moment when one of them couldn’t give the right amount of candy. They don’t consider the candies they have got from the opponent, as their own. We have to find, who is the first can’t give the right amount of candy.

So, if the input is like a = 7; b = 6, then the output will be Amal, because initially Amal gave 1, Bimal gave 2, then Amal gave 3 and Bimal gave 4, now in this turn Amal has to give 5 candies but he has only 4.


To solve this, we will follow these steps −

x := square root of a
if x * (x + 1) > b, then:
   return "Bimal"
   return "Amal"


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
string solve(int a, int b){
   int x = sqrt(a);
   if (x * (x + 1) > b)
      return "Bimal";
      return "Amal";
int main(){
   int a = 7;
   int b = 6;
   cout << solve(a, b) << endl;


7, 6


Updated on 29-Mar-2022 11:17:25