I am writing a grocery shopping program.
I want to calculate the smallest number of items I have to buy to reach the smallest whole dollar amount.
For example:
Candies cost 0.11. You need 100 candies to reach the nearest whole dollar amount 11
(100 * 0.11) = 11.0
Apples cost 0.5 each. you need 2 apples to reach the nearest dollar amount $1
(2 * 0.5) = 1.0
Ice Cream costs 4.82 You need 50 ice creams to reach the nearest whole dollar amount 241
(50 * 4.82) = 241.0
I THINK I am trying to solve the equation X % Y = 0 for X. X must be an integer. Y can be any positive rational number.
I can brute force the answer by running a simple loop:
var result : Number = ITEM_COST;
while(result % 1 != 0)
{
result += ITEM_COST
}
return result / ITEM_COST;
However, I would like to have a more elegant calculation, if possible.
Assuming that the fractional part of $Y$ has at most $2$ decimal digits, the value of $X$ is $\frac{100}{\gcd(100Y,100)}$
Here is pseudo-code for calculating the GCD of two positive integers: