Skip to content

Instantly share code, notes, and snippets.

@vo
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vo/9262564 to your computer and use it in GitHub Desktop.
Save vo/9262564 to your computer and use it in GitHub Desktop.
Divide two unsigned ints without division operator
#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);
}
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