Distribute N candies among K people

Sanyam has ‘N’ candies, he wants to distribute that into ‘K’ of his friends. He made his ‘K’ friends stand in line, in increasing order of his likeness. Not being so smart he gives 1 candy to the first friend, 2 to the second person, and so on till the kth person. In the next turn, the first person gets ‘K + 1’ candies, the second person gets ‘K + 2’ candies, and so on.

While distributing the candies, if at a turn, the number of candies to be given to a friend is less than the required candies, then that friend gets all the remaining candies and Sanyam stops the distribution.

Your task is to find the total number of candies every person has at the end.

Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The next ‘T’ lines represent the ‘T’ test cases.

The first and only line of each test case contains two space-separated integers ‘N’ and ‘K’ denoting the number of candies and number of friends respectively.
Output Format:
For each test case, return the total number of candies every person has at the end.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given functions.
Constraints:
1 <= T <= 50
1 <= N <= 10^9
1 <= K <= 10^5

Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force

Here we can simply use the concept of brute force.

  • We initialize an array with 0 elements.
  • Then we make a variable and initialize it with 1(let’s call it “increment”). This variable is use...read more
CodingNinjas
author
2y
Mathematical approach
  • We initialize an array with 0 elements.
  • We know that 1 + 2 + 3……+ r = ((r * (r + 1)) / 2).
  • We can sum of natural numbers till the last term of the series which will be (turns * K) a...read more
CodingNinjas
author
2y
Binary search

Here we can simply use the concept of binary search.

  • We initialize an array with 0 elements.
  • We use binary search to find the largest ‘x’ which satisfies x * (x + 1) <= (2 * N). (Here x ...read more
Add answer anonymously...
GeeksForGeeks Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter