Advertisement
pushrbx

Divide a number without using *, /, +, -, % operators

Sep 23rd, 2013
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.49 KB | None | 0 0
  1. // http://stackoverflow.com/questions/11694546/divide-a-number-by-3-without-using-operators
  2. // replaces the + operator
  3. int add(int x, int y) {
  4.     int a, b;
  5.     do {
  6.         a = x & y;
  7.         b = x ^ y;
  8.         x = a << 1;
  9.         y = b;
  10.     } while (a);
  11.     return b;
  12. }
  13.  
  14. int divideby3 (int num) {
  15.     int sum = 0;
  16.     while (num > 3) {
  17.         sum = add(num >> 2, sum);
  18.         num = add(num >> 2, num & 3);
  19.     }
  20.     if (num == 3)
  21.         sum = add(sum, 1);
  22.     return sum;
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement