Compute x/y (5.6)

#1

I looked at the solution, and understand the method (maybe not fully which leads me to the question below).

Is there a reason why we have the following in the code

int power = 32;

Why do we start with power as 32 ? and not higher or any other number?

Also, if y is zero (0), the code (at least the Java version) does not protect against divide by zero - and runs indefinitely.

0 Likes

#2

Hey ashkar,

Thanks for the reply, and the reason we use 32 is because we assume the quotient is within 32 bit (remember that both x and y are 32-bit integers). So there is no need to go higher than that.

Also, since anything divides by 0 is ill-defined as our book does not handle illegal case which districts readers from the main algorithm and those handling is usually involves easy boilerplate code.

Please let me know if you have any other question.

0 Likes

#3

Thank you so much for your quick response ! :smile:

I had a feeling that’s why it is 32 bit, but was confused. Maybe the fact that the data type used in the code - including the return type were all long which are 64 bits threw me off.

Thanks for the note on why the boiler plate code was avoided.

0 Likes

#4

The two parameters using in this code are long type. I think in java the long is 64 bit, should we use int as parameter instead?

0 Likes

#5

Hi @Hitchcock,

It is because the missing feature before Java 1.8 of unsigned int. So we have to use long as an unsigned int. We are looking at using Java 1.8 to replace unsigned int.

0 Likes