1

I wrote a simple piece of code - ceil1. Since it failed my test cases after rewriting same code - ceil worked.

public class Test {
public static void main(String args[]){
    System.out.println(ceil(3, 2)); //getting 2
    System.out.println(ceil1(3, 2)); //getting 1
}

public static int ceil(int dividend, int divisor){
    int a = dividend/divisor;
    int b = dividend%divisor == 0 ? 0:1;
    return a+b;
}

public static int ceil1(int dividend, int divisor){
    return dividend/divisor + dividend%divisor == 0 ? 0:1;
}}

I can't put my finger on what is difference between these two? Possibly intermediate calculation/operator precedence causing this haywire.

Amit G
  • 2,293
  • 3
  • 24
  • 44

4 Answers4

3

In

return dividend/divisor + dividend%divisor == 0 ? 0:1;

The addition of

dividend/divisor + dividend%divisor

is performed and then the result is compared to 0.

You want:

return dividend/divisor + (dividend%divisor == 0 ? 0:1);

or

return dividend/divisor + (dividend%divisor == 0) ? 0:1;

In order that only dividend%divisor will be compared to 0.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

The addition (+) operator has a higher precedence than the ternary (?) operator. You can surround that expression with parenthesis to get the behavior you want:

public static int ceil1(int dividend, int divisor){
    return dividend/divisor + (dividend%divisor == 0 ? 0:1);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

All of /, +, % have a higher precedence than ==, hence

dividend/divisor + dividend%divisor == 0 ? 0:1

is equivalent to

(dividend/divisor + dividend%divisor) == 0 ? 0:1

So you will always get either 0 or 1 from this.

daniu
  • 14,137
  • 4
  • 32
  • 53
1

Irrespective of the precedence issue, your code produces incorrect answers.

For example, ceil(-5, 3) returns 0, whereas Math,ceil(-5.0 / 3.0) returns -1 (the "un-ceiled" value is -1.666667).

You will get the correct answer if you use a simpler approach:

(dividend + divisor - 1) / divisor

Ideone demo

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • I was doing it only for positive integers. But this is awesome. – Amit G Mar 08 '18 at 08:34
  • @AmitG if you're only doing it for positive integers, make sure you add precondition checks to your method so you fail with negative integers; it is far better to fail than to give the wrong answer. – Andy Turner Mar 08 '18 at 08:40