Friday, August 7, 2020

Divisibility

 One of my friends asked me to come up with a solution for this problem in Java/C#

public int isXDivisibleByY(int x, int y)
{
/* 
The method should meet the following conditions:

1. Method returns 1, if X can   be divided by Y without a remainder
2. Method returns 0, if X can't be divided by Y without a remainder
3. Solution must not include any conditional checks (if condition, equality operators, the ternary and null-coalescing operators etc.)
4. Solution must not include any exception handling (try-catch-finally)
5. It should work all kinds of inputs of x and y
*/
}

Challenges & Solutions

  1. I had failed to notice that there is no straight forward way to cast a boolean to int in Java. This is missing in Java because Java designers (correctly) recognized that the boolean / integer overloading in C and C++ was a significant source of errors. Source (https://stackoverflow.com/questions/16281760/why-doesnt-java-allow-casting-boolean-int). Thank God, there's this weird compareTo method in Boolean.
  2. Without a try-catch-Finally, Handling divide by Zero gracefully is not easy. However a simple cast of float to the divisor is handy. Thanks to the division rules https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.2


Final Solution by me:

public int isXDivisibleByY(int x, int y )
{
return 1 - Boolean.compare((x%(float)y) > 0, false) ;
}

Well, compare method may use conditionals internally but I guess, this is one possible solution without a visible conditional...

Next thing to try: Applying https://en.wikipedia.org/wiki/Divisibility_rule