PROBLEM LINKS
DIFFICULTY
CAKEWALK
PREREQUISITES
Simple Math
PROBLEM
You wish to equally distribute N candies among M people, using the following algorithm
nCandies = 0 candies-with-each-person = 0 while nCandies ≥ M ++candies-with-each-person nCandies = nCandies - M
Print the values of candies-with-each-person and nCandies at the end of the algorithm.
EXPLANATION
The given algorithm is an ad-hoc simultation of the division operation.
At the end of the algorithm, it is clear that
candies-with-each-person = quotient of N divided by M
and
nCandies = remainder of N divided by M
CODING COMMENTARY
There were two common pitfalls. The hint to both of them lay discreetly within the Constraints section.
##M could be equal to 0
A lot of submissions received
Runtime Error: Floating Point Exception
verdict because of this pitfall.
The exact error of course is the attempted division by 0. Handling it as a special case is one solution.
##N,M could be equal to 8,589,934,591
This typically led to a Wrong Answer verdict. The range of integers handled by the 32-bit signed integer datatype is typically
[-2147483648 2147483647]
One had to use 64-bit integer datatype to solve this problem. This means
- long long in C/C++ - as CodeChef uses the GNU C++ Compiler
- long in Java
PSEUDO CODE
Given: N, M if M == 0 return { candies-with-each-person = 0, nCandies = N } else return { candies-with-each-person = N / M, nCandies = N % M }
Here, we assume that
- N and M are 64-bit integers
- % is the modulo operation
SETTER’S SOLUTION
Can be found here.
TESTER’S SOLUTION
Can be found here.