-6

There is a problem I am supposed to solve that is normally easy, but it has a catch.

There are 2 types of candy. One type weighs m1 kg and is sold for s1 Euro. A second type weighs m2 kg and is sold for s2 Euro. All numbers are integers.

The question is, which type of candy costs more per kg?

The catch is, you can't use divide operation at all, neither / nor %.

For example, if we have the numbers as m1=2, s1=17, m2=3, and s2=14 then the answer needs to be that the first candies are more expensive as 17/2=8.5 and 14/3=4.(3).

As I am a C++ student, I am restricted to use only that which has been taught so far in the class to determine the more expensive candy. The only thing we learned so far was + - / * % and if statement with else. Also == > < && ||.

jxh
  • 69,070
  • 8
  • 110
  • 193
Sigmar
  • 5
  • 3

1 Answers1

1

Compare Xs1 * m2 with Ys2 * m1. If X > Y, then s1 / m1 > s2 / m2.

No division is required to do the comparison.

The caveat to this solution is that s1, s2, m1, and m2 should all have the same sign, and m1 and m2 should be non-zero.


Let's assume all the values are positive integers (hence, greater than 0). Consequently m1 * m2 is positive as well. Let z be the number such that:

z + (s1 / m1) = s2 / m2

By multiplying by m1 * m2 on both sides, we get:

z' + (s1 * m2) = s2 * m1z'z × (m1 * m2)

Since z and z' have the same sign, the relational order of s1 / m1 and s1 / m2 is the same as the relational order of s1 * m2 and s2 * m1.

jxh
  • 69,070
  • 8
  • 110
  • 193