Integer division c++

Integer division problem definition

Given the following function which computes integer division. Debug the code and identify the major bugs. Modify the code to fix those bugs. Assume all integer variables are within range and no overflow is about to happen.

Integer division explained

(1) If the numerator is equal to the denominator the function must return 1 but in this case it returns 0 which is wrong (2) if the denominator is 0 then the while will not end if the numerator is positive. If the numerator is negative then the function will return 0 as the final result which is wrong as we all know that division by zero is not allowed (3) If the numerator is positive and the denominator is negative then the while loop will not end because the numerator will keep increasing.

The solution is to operate on positive integers then return the right sign at the end based on the sign of input integers. We also need to handle the case of division by zero and the case when numerator is equal to denominator.

Integer division algorithm

Here is an integer division example in C++

Please use the comments section below for feedback. You may also share it with friends, just click on the sharing buttons below.

Tags:
One Comment

Add a Comment

Your email address will not be published. Required fields are marked *