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.

3
  • 1
    Why not just (a+b-1)/b? Commented Mar 8, 2018 at 8:05
  • 1
    Try adding some brackets in ceil1 Commented Mar 8, 2018 at 8:05
  • 3
    Yes, it's operator precedence causing your issue. Add brackets. Commented Mar 8, 2018 at 8:05

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

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.

Comments

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

2 Comments

I was doing it only for positive integers. But this is awesome.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.