- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to find hoe many children will get candies while distributing them maintaining the rules in Python

Suppose we have k number of candies. We have to distribute them among children. Now there are some rules

- ith child will get i^2 number of candies
- any children at index i will not get any candy until all children from index 1 to i-i are served
- If ith children does not get i^2 number of candies, then that is not a valid serve.

So, if the input is like k = 20, then the output will be 3 because, first one will get 1, second one will get 2^2 = 4, third one will get 3^2 = 9, but fourth one needs 4^2 = 16, but we have only 6 candies left, so this is not a valid distribution, so only three children will be served.

To solve this, we will follow these steps −

- left := 0, right := k
- while right - left > 1, do
- mid := floor of (left + right) / 2
- if floor of (mid * (mid + 1) * (2 * mid + 1) / 6) > k, then
- right := mid

- otherwise,
- left := mid

- if right *(right + 1) *(2 * right + 1) <= k * 6, then
- return right

- return left

## Example

Let us see the following implementation to get better understanding −

def solve(k): left = 0 right = k while (right - left > 1): mid = (left + right) // 2 if (mid * (mid + 1) * (2 * mid + 1) // 6 > k): right = mid else: left = mid if (right * (right + 1) * (2 * right + 1) <= k * 6): return right return left k = 20 print(solve(k))

## Input

20

## Output

3

- Related Articles
- Program to find how many years it will take to reach t amount in Python
- Python Program to find out how many times the balls will collide in a circular tube
- Program to count how many swimmers will win the final match in Python
- Distribute Candies to People in Python
- C++ program to check whether we can distribute bags so that two friends will get same amount of candies
- Program to find nth sequence after following the given string sequence rules in Python
- Find the minimum and maximum amount to buy all N candies in Python
- Program to find how many lines intersect in Python
- Distributing all balls without repetition in C++ Program
- I often coin many words in English. How to get them into the dictionary?
- C++ code to count children who will get ball after each throw
- Reversing a string while maintaining the position of spaces in JavaScript
- C++ Program to find table plate ordering maintaining given conditions
- Rules to be followed while making Investment Decisions
- Maximum Candies You Can Get from Boxes in C++

Advertisements