Distribute chocolates

You have c number of chocolates that you want to distribute between your students. The intelligence level of the students is not the same, therefore, you decide to distribute the chocolates in such a way that a smarter student gets strictly more chocolates than the ones who are less smarter.

The difference between the chocolates received by any two adjacent students must be exactly one. Formally, if the least intelligent student gets k chocolates, then others must get k + 1, k + 2, k + 3,... At the same time, your task is to minimize the number of chocolates that are left (if any) after distributing those among students. Determine the minimum number of chocolates left.

Example:

Input:  c=20 , n=3
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;

long long distributeChocolates(long long clong long n)
{

    long long m = c;
    if (c <= n)
        return c;
    else
    {
        long long sum = n * (n + 1) / 2;
        c = c - sum;
        if (c < 0)
            return m;
        else
        {
            long long p = c / n;
            c = c - p * n;
            return c;
        }
    }
}
int main()
{
    long long c = 20n = 3;

    cout << distributeChocolates(cn);

    return 0;
}


No comments:

Post a Comment