Last active
August 29, 2015 13:56
-
-
Save vo/9262564 to your computer and use it in GitHub Desktop.
Divide two unsigned ints without division operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
typedef unsigned int UINT; | |
// does not handle overflow or negative numbers | |
UINT divide_naive(UINT a, UINT b) | |
{ | |
UINT result; | |
while (b < a) { | |
UINT k=0, b2k = b; | |
while(b2k << 1 < a) | |
{ | |
k++; | |
b2k <<= 1; | |
} | |
a -= b2k; | |
result += (1 << k); | |
} | |
return result; | |
} | |
void main() | |
{ | |
UINT a,b; | |
printf("Enter unsigned value a: "); | |
scanf("%u", &a); | |
printf("Enter unsigned value b: "); | |
scanf("%u", &b); | |
UINT c = divide_naive(a, b); | |
printf("divide_naive:\t(%u / %u) = %u\n", a, b, c); | |
printf("correct answer:\t(%u / %u) = %u\n", a, b, a/b); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def divide_naive(a,b): | |
'''Divide a by b and return the result. | |
Assumes a and b are longs. | |
Does not handle overflow or negative numbers''' | |
result = 0 | |
while b < a: | |
k = 0 | |
b2k = b | |
while b2k << 1 < a: | |
k += 1 | |
b2k <<= 1; | |
a -= b2k | |
result += (1 << k) | |
return result | |
a = long(input("Enter unsigned integer a: ")) | |
b = long(input("Enter unsigned integer b: ")) | |
print "divide_naive:\t(%u, %u) = %u" % (a, b, divide_naive(a,b)) | |
print "correct answer:\t(%u, %u) = %u" % (a, b, int(a/b)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment