Skip to content

Instantly share code, notes, and snippets.

@wnds
Last active December 19, 2015 07:39
Show Gist options
  • Save wnds/5920164 to your computer and use it in GitHub Desktop.
Save wnds/5920164 to your computer and use it in GitHub Desktop.
Perform Integer Division Without Using Either the / or * Operators
public class Answer28 {
private static long dividend = 1;
private static long divisor = 1;
public static long divideOne(long dividend, long divisor) {
long quotient = 0;
if(dividend <= 0 || divisor <= 0 || dividend < divisor)
return 0;
while (dividend >= divisor) {
dividend -= divisor;
quotient++;
}
System.out.println("(divideOne): Answer: " + quotient);
return quotient;
}
//http://www.dragonwins.com/domains/getteched/de248/binary_division.htm
public static long divideTwo(long dividend, long divisor) {
long quotient = 0;
if(dividend <= 0 || divisor <= 0 || dividend < divisor)
return 0;
// term * divisor should be close to dividend
long term = 1;
//System.out.println(dividend + " " + divisor + " " + term + " " + quotient);
while((term < Math.pow(2,64 - 1)) && (divisor < dividend))
{
divisor = divisor << 1;
term = term << 1;
//System.out.println(dividend + " " + divisor + " " + term + " " + quotient);
}
while(term >= 1)
{
if(divisor <= dividend)
{
//System.out.println(dividend + " " + divisor + " " + term + " " + quotient);
quotient += term;
dividend = dividend - divisor;
}
//System.out.println(dividend + " " + divisor + " " + term + " " + quotient);
divisor = divisor >> 1;
term = term >> 1;
}
System.out.println("(divideTwo): Answer: " + quotient);
return quotient;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment