Implement division with bit-wise operator - bit-manipulation
How can I implement division using bit-wise operators (not just division by powers of 2)?
Describe it in detail.
The standard way to do division is by implementing binary long-division. This involves subtraction, so as long as you don't discount this as not a bit-wise operation, then this is what you should do. (Note that you can of course implement subtraction, very tediously, using bitwise logical operations.)
In essence, if you're doing Q = N/D:
Align the most-significant ones of N and D.
Compute t = (N - D);.
If (t >= 0), then set the least significant bit of Q to 1, and set N = t.
Left-shift N by 1.
Left-shift Q by 1.
Go to step 2.
Loop for as many output bits (including fractional) as you require, then apply a final shift to undo what you did in Step 1.
Division of two numbers using bitwise operators.
#include <stdio.h>
int remainder, divisor;
int division(int tempdividend, int tempdivisor) {
int quotient = 1;
if (tempdivisor == tempdividend) {
remainder = 0;
return 1;
} else if (tempdividend < tempdivisor) {
remainder = tempdividend;
return 0;
}
do{
tempdivisor = tempdivisor << 1;
quotient = quotient << 1;
} while (tempdivisor <= tempdividend);
/* Call division recursively */
quotient = quotient + division(tempdividend - tempdivisor, divisor);
return quotient;
}
int main() {
int dividend;
printf ("\nEnter the Dividend: ");
scanf("%d", ÷nd);
printf("\nEnter the Divisor: ");
scanf("%d", &divisor);
printf("\n%d / %d: quotient = %d", dividend, divisor, division(dividend, divisor));
printf("\n%d / %d: remainder = %d", dividend, divisor, remainder);
getch();
}
int remainder =0;
int division(int dividend, int divisor)
{
int quotient = 1;
int neg = 1;
if ((dividend>0 &&divisor<0)||(dividend<0 && divisor>0))
neg = -1;
// Convert to positive
unsigned int tempdividend = (dividend < 0) ? -dividend : dividend;
unsigned int tempdivisor = (divisor < 0) ? -divisor : divisor;
if (tempdivisor == tempdividend) {
remainder = 0;
return 1*neg;
}
else if (tempdividend < tempdivisor) {
if (dividend < 0)
remainder = tempdividend*neg;
else
remainder = tempdividend;
return 0;
}
while (tempdivisor<<1 <= tempdividend)
{
tempdivisor = tempdivisor << 1;
quotient = quotient << 1;
}
// Call division recursively
if(dividend < 0)
quotient = quotient*neg + division(-(tempdividend-tempdivisor), divisor);
else
quotient = quotient*neg + division(tempdividend-tempdivisor, divisor);
return quotient;
}
void main()
{
int dividend,divisor;
char ch = 's';
while(ch != 'x')
{
printf ("\nEnter the Dividend: ");
scanf("%d", ÷nd);
printf("\nEnter the Divisor: ");
scanf("%d", &divisor);
printf("\n%d / %d: quotient = %d", dividend, divisor, division(dividend, divisor));
printf("\n%d / %d: remainder = %d", dividend, divisor, remainder);
_getch();
}
}
I assume we are discussing division of integers.
Consider that I got two number 1502 and 30, and I wanted to calculate 1502/30. This is how we do this:
First we align 30 with 1501 at its most significant figure; 30 becomes 3000. And compare 1501 with 3000, 1501 contains 0 of 3000. Then we compare 1501 with 300, it contains 5 of 300, then compare (1501-5*300) with 30. At so at last we got 5*(10^1) = 50 as the result of this division.
Now convert both 1501 and 30 into binary digits. Then instead of multiplying 30 with (10^x) to align it with 1501, we multiplying (30) in 2 base with 2^n to align. And 2^n can be converted into left shift n positions.
Here is the code:
int divide(int a, int b){
if (b != 0)
return;
//To check if a or b are negative.
bool neg = false;
if ((a>0 && b<0)||(a<0 && b>0))
neg = true;
//Convert to positive
unsigned int new_a = (a < 0) ? -a : a;
unsigned int new_b = (b < 0) ? -b : b;
//Check the largest n such that b >= 2^n, and assign the n to n_pwr
int n_pwr = 0;
for (int i = 0; i < 32; i++)
{
if (((1 << i) & new_b) != 0)
n_pwr = i;
}
//So that 'a' could only contain 2^(31-n_pwr) many b's,
//start from here to try the result
unsigned int res = 0;
for (int i = 31 - n_pwr; i >= 0; i--){
if ((new_b << i) <= new_a){
res += (1 << i);
new_a -= (new_b << i);
}
}
return neg ? -res : res;
}
Didn't test it, but you get the idea.
This solution works perfectly.
#include <stdio.h>
int division(int dividend, int divisor, int origdiv, int * remainder)
{
int quotient = 1;
if (dividend == divisor)
{
*remainder = 0;
return 1;
}
else if (dividend < divisor)
{
*remainder = dividend;
return 0;
}
while (divisor <= dividend)
{
divisor = divisor << 1;
quotient = quotient << 1;
}
if (dividend < divisor)
{
divisor >>= 1;
quotient >>= 1;
}
quotient = quotient + division(dividend - divisor, origdiv, origdiv, remainder);
return quotient;
}
int main()
{
int n = 377;
int d = 7;
int rem = 0;
printf("Quotient : %d\n", division(n, d, d, &rem));
printf("Remainder: %d\n", rem);
return 0;
}
Implement division without divison operator:
You will need to include subtraction. But then it is just like you do it by hand (only in the basis of 2). The appended code provides a short function that does exactly this.
uint32_t udiv32(uint32_t n, uint32_t d) {
// n is dividend, d is divisor
// store the result in q: q = n / d
uint32_t q = 0;
// as long as the divisor fits into the remainder there is something to do
while (n >= d) {
uint32_t i = 0, d_t = d;
// determine to which power of two the divisor still fits the dividend
//
// i.e.: we intend to subtract the divisor multiplied by powers of two
// which in turn gives us a one in the binary representation
// of the result
while (n >= (d_t << 1) && ++i)
d_t <<= 1;
// set the corresponding bit in the result
q |= 1 << i;
// subtract the multiple of the divisor to be left with the remainder
n -= d_t;
// repeat until the divisor does not fit into the remainder anymore
}
return q;
}
The below method is the implementation of binary divide considering both numbers are positive. If subtraction is a concern we can implement that as well using binary operators.
Code
-(int)binaryDivide:(int)numerator with:(int)denominator
{
if (numerator == 0 || denominator == 1) {
return numerator;
}
if (denominator == 0) {
#ifdef DEBUG
NSAssert(denominator == 0, #"denominator should be greater then 0");
#endif
return INFINITY;
}
// if (numerator <0) {
// numerator = abs(numerator);
// }
int maxBitDenom = [self getMaxBit:denominator];
int maxBitNumerator = [self getMaxBit:numerator];
int msbNumber = [self getMSB:maxBitDenom ofNumber:numerator];
int qoutient = 0;
int subResult = 0;
int remainingBits = maxBitNumerator-maxBitDenom;
if (msbNumber >= denominator) {
qoutient |=1;
subResult = msbNumber - denominator;
}
else {
subResult = msbNumber;
}
while (remainingBits>0) {
int msbBit = (numerator & (1 << (remainingBits-1)))>0 ? 1 : 0;
subResult = (subResult << 1) |msbBit;
if (subResult >= denominator) {
subResult = subResult-denominator;
qoutient = (qoutient << 1) | 1;
}
else {
qoutient = qoutient << 1;
}
remainingBits--;
}
return qoutient;
}
-(int)getMaxBit:(int)inputNumber
{
int maxBit =0;
BOOL isMaxBitSet = NO;
for (int i=0; i<sizeof(inputNumber)*8; i++) {
if (inputNumber & (1 << i) ) {
maxBit = i;
isMaxBitSet=YES;
}
}
if (isMaxBitSet) {
maxBit += 1;
}
return maxBit;
}
-(int)getMSB:(int)bits ofNumber:(int)number
{
int numbeMaxBit = [self getMaxBit:number];
return number >> (numbeMaxBit -bits);
}
For integers:
public class Division {
public static void main(String[] args) {
System.out.println("Division: " + divide(100, 9));
}
public static int divide(int num, int divisor) {
int sign = 1;
if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
sign = -1;
return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
}
public static int divide(int num, int divisor, int sum) {
if (sum > num) {
return 0;
}
return 1 + divide(num, divisor, sum + divisor);
}
}
With the usual caveats about C's behaviour with shifts, this ought to work for unsigned quantities regardless of the native size of an int...
static unsigned int udiv(unsigned int a, unsigned int b) {
unsigned int c = 1, result = 0;
if (b == 0) return (unsigned int)-1 /*infinity*/;
while (((int)b > 0) && (b < a)) { b = b<<1; c = c<<1; }
do {
if (a >= b) { a -= b; result += c; }
b = b>>1; c = c>>1;
} while (c);
return result;
}
This is my solution to implement division with only bitwise operations:
int align(int a, int b) {
while (b < a) b <<= 1;
return b;
}
int divide(int a, int b) {
int temp = b;
int result = 0;
b = align(a, b);
do {
result <<= 1;
if (a >= b) {
// sub(a,b) is a self-defined bitwise function for a minus b
a = sub(a,b);
result = result | 1;
}
b >>= 1;
} while (b >= temp);
return result;
}
Unsigned Long Division (JavaScript) - based on Wikipedia article: https://en.wikipedia.org/wiki/Division_algorithm:
"Long division is the standard algorithm used for pen-and-paper division of multi-digit numbers expressed in decimal notation. It shifts gradually from the left to the right end of the dividend, subtracting the largest possible multiple of the divisor (at the digit level) at each stage; the multiples then become the digits of the quotient, and the final difference is then the remainder.
When used with a binary radix, this method forms the basis for the (unsigned) integer division with remainder algorithm below."
Function divideWithoutDivision at the end wraps it to allow negative operands. I used it to solve leetcode problem "Product of Array Except Self"
function longDivision(N, D) {
let Q = 0; //quotient and remainder
let R = 0;
let n = mostSignificantBitIn(N);
for (let i = n; i >= 0; i--) {
R = R << 1;
R = setBit(R, 0, getBit(N, i));
if (R >= D) {
R = R - D;
Q = setBit(Q, i, 1);
}
}
//return [Q, R];
return Q;
}
function mostSignificantBitIn(N) {
for (let i = 31; i >= 0; i--) {
if (N & (1 << i))
return i ;
}
return 0;
}
function getBit(N, i) {
return (N & (1 << i)) >> i;
}
function setBit(N, i, value) {
return N | (value << i);
}
function divideWithoutDivision(dividend, divisor) {
let negativeResult = (dividend < 0) ^ (divisor < 0);
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
let quotient = longDivision(dividend, divisor);
return negativeResult ? -quotient : quotient;
}
All these solutions are too long. The base idea is to write the quotient (for example, 5=101) as 100 + 00 + 1 = 101.
public static Point divide(int a, int b) {
if (a < b)
return new Point(0,a);
if (a == b)
return new Point(1,0);
int q = b;
int c = 1;
while (q<<1 < a) {
q <<= 1;
c <<= 1;
}
Point r = divide(a-q, b);
return new Point(c + r.x, r.y);
}
public static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int compare(Point b) {
if (b.x - x != 0) {
return x - b.x;
} else {
return y - b.y;
}
}
#Override
public String toString() {
return " (" + x + " " + y + ") ";
}
}
Since bit wise operations work on bits that are either 0 or 1, each bit represents a power of 2, so if I have the bits
1010
that value is 10.
Each bit is a power of two, so if we shift the bits to the right, we divide by 2
1010 --> 0101
0101 is 5
so, in general if you want to divide by some power of 2, you need to shift right by the exponent you raise two to, to get that value
so for instance, to divide by 16, you would shift by 4, as 2^^4 = 16.
Related
Looking for nbit adder in c++
I was trying to build 17bit adder, when overflow occurs it should round off should appear just like int32. eg: In int32 add, If a = 2^31 -1 int res = a+1 res= -2^31-1 Code I tried, this is not working & is there a better way. Do I need to convert decimal to binary & then perform 17bit operation int addOvf(int32_t result, int32_t a, int32_t b) { int max = (-(0x01<<16)) int min = ((0x01<<16) -1) int range_17bit = (0x01<<17); if (a >= 0 && b >= 0 && (a > max - b)) { printf("...OVERFLOW.........a=%0d b=%0d",a,b); } else if (a < 0 && b < 0 && (a < min - b)) { printf("...UNDERFLOW.........a=%0d b=%0d",a,b); } result = a+b; if(result<min) { while(result<min){ result=result + range_17bit; } } else if(result>min){ while(result>max){ result=result - range_17bit; } } return result; } int main() { int32_t res,x,y; x=-65536; y=-1; res =addOvf(res,x,y); printf("Value of x=%0d y=%0d res=%0d",x,y,res); return 0; }
You have your constants for max/min int17 reversed and off by one. They should be max_int17 = (1 << 16) - 1 = 65535 and min_int17 = -(1 << 16) = -65536. Then I believe that max_int_n + m == min_int_n + (m-1) and min_int_n - m == max_int_n - (m-1), where n is the bit count and m is some integer in [min_int_n, ... ,max_int_n]. So putting that all together the function to treat two int32's as though they are int17's and add them would be like int32_t add_as_int17(int32_t a, int32_t b) { static const int32_t max_int17 = (1 << 16) - 1; static const int32_t min_int17 = -(1 << 16); auto sum = a + b; if (sum < min_int17) { auto m = min_int17 - sum; return max_int17 - (m - 1); } else if (sum > max_int17) { auto m = sum - max_int17; return min_int17 + (m - 1); } return sum; } There is probably some more clever way to do that but I believe the above is correct, assuming I understand what you want.
Division using right shift operator gives TLE while normal division works fine
I'm trying to submit this leetcode problem Pow(x,n) using iterative approach. double poww(double x, int n) { if (n == 0) return 1; double ans = 1; double temp = x; while (n) { if (n & 1) { ans *= temp; } temp *= temp; n = (n >> 1); } return ans; } double myPow(double x, int n) { if (n == 0) return 1.0; if (n < 0) return 1 / poww(x, abs(n)); return poww(x, n); } This code is giving time limit exceed error but when I change the right shift operator >> with normal division operator, the code works just fine. Working code with division operator double poww(double x, int n) { if (n == 0) return 1; double ans = 1; double temp = x; while (n) { if (n & 1) { ans *= temp; } temp *= temp; n /= 2; } return ans; } double myPow(double x, int n) { if (n == 0) return 1.0; if (n < 0) return 1 / poww(x, abs(n)); return poww(x, n); } I don't know what I'm missing here.
The problem is the given input range for "n". Let us look at the constraints again: The problem is the smallest number for n, which is -2^31 and that is equal to -2147483648. But the valid range for an integer is -2^31 ... 2^31-1 which is -2147483648 ... 2147483647. Then you try to use the abs function on -2147483648. But since there is no positive equivalent for that in the integer domain (on your machine), the number stays negative. And then you get the wrong result, because your n will be negative in your "poww" function. Presumably on your machine long is the same as int, so, a 4 byte variable. If you change your interface to use a long long variable, it will work. Result maybe "inf" for big numbers or 0. Please check the below code: #include <iostream> #include <cmath> long double poww(double x, long long n) { if (n == 0) return 1; long double ans = 1; long double temp = x; while (n) { if (n & 1) { ans *= temp; } temp *= temp; n = (n >> 1); } return ans; } long double myPow(double x, long long n) { if (n == 0) return 1.0; if (n < 0) return 1 / poww(x, std::llabs(n)); return poww(x, n); } int main() { std::cout << myPow(1, -2147483648) << '\n'; }
Mod power or totient logic issue
Here is some code I adapted that deals with the euler totient function and a power mod function. Every n, f2 is always 3 instead of a variety of numbers. Does anyone see an error? phi(n) and modpow(n) both seem to work fine. #include <iostream> using namespace std; int gcd(int a, int b) { while (b != 0) { int c = a % b; a = b; b = c; } return a; } int phi(int n) { int x = 0; for (int i=1; i<=n; i++) { if (gcd(n, i) == 1) x++; } return x; } int modpow(int base, int exp, int mod) // from stackoverflow { base %= mod; long long result = 1; while (exp > 0) { if (exp & 1) result = (result * base) % mod; base = (base * base) % mod; exp >>= 1; } return result; } int f2(int n) // f(f(n)) mod n { long long a = modpow(2, n, phi(n)) + 1; return (modpow(2, a, n) + 1) % n; } // ... int main() { int n = 520001; while (true) { cout << "f2 " << f2(n) << endl; if (f2(n) == 0) { // ... } n += 2; } return 0; } Values of f2(n) should be 9, 458278, 379578, ...
base*base will exceed the size of an int if base >= 65536. Try this fix, seems to work: int modpow(int base, int exp, int mod) // from stackoverflow { base %= mod; long long result = 1; while (exp > 0) { if (exp & 1) result = (result * base) % mod; base = (int)(((long long)base * (long long)base) % mod); exp >>= 1; } return (int) result; }
What is the fastest way to compute large power of 2 modulo a number
For 1 <= N <= 1000000000, I need to compute 2N mod 1000000007, and it must be really fast! My current approach is: ull power_of_2_mod(ull n) { ull result = 1; if (n <= 63) { result <<= n; result = result % 1000000007; } else { ull one = 1; one <<= 63; while (n > 63) { result = ((result % 1000000007) * (one % 1000000007)) % 1000000007; n -= 63; } for (int i = 1; i <= n; ++i) { result = (result * 2) % 1000000007; } } return result; } but it doesn't seem to be fast enough. Any idea?
This will be faster (code in C): typedef unsigned long long uint64; uint64 PowMod(uint64 x, uint64 e, uint64 mod) { uint64 res; if (e == 0) { res = 1; } else if (e == 1) { res = x; } else { res = PowMod(x, e / 2, mod); res = res * res % mod; if (e % 2) res = res * x % mod; } return res; }
This method doesn't use recursion with O(log(n)) complexity. Check this out. #define ull unsigned long long #define MODULO 1000000007 ull PowMod(ull n) { ull ret = 1; ull a = 2; while (n > 0) { if (n & 1) ret = ret * a % MODULO; a = a * a % MODULO; n >>= 1; } return ret; } And this is pseudo from Wikipedia (see Right-to-left binary method section) function modular_pow(base, exponent, modulus) Assert :: (modulus - 1) * (base mod modulus) does not overflow base result := 1 base := base mod modulus while exponent > 0 if (exponent mod 2 == 1): result := (result * base) mod modulus exponent := exponent >> 1 base := (base * base) mod modulus return result
You can solve it in O(log n). For example, for n = 1234 = 10011010010 (in base 2) we have n = 2 + 16 + 64 + 128 + 1024, and thus 2^n = 2^2 * 2^16 * 2^64 * 2^128 * 2 ^ 1024. Note that 2^1024 = (2^512)^2, so that, given you know 2^512, you can compute 2^1024 in a couple of operations. The solution would be something like this (pseudocode): const ulong MODULO = 1000000007; ulong mul(ulong a, ulong b) { return (a * b) % MODULO; } ulong add(ulong a, ulong b) { return (a + b) % MODULO; } int[] decompose(ulong number) { //for 1234 it should return [1, 4, 6, 7, 10] } //for x it returns 2^(2^x) mod MODULO // (e.g. for x = 10 it returns 2^1024 mod MODULO) ulong power_of_power_of_2_mod(int power) { ulong result = 1; for (int i = 0; i < power; i++) { result = mul(result, result); } return result; } //for x it returns 2^x mod MODULO ulong power_of_2_mod(int power) { ulong result = 1; foreach (int metapower in decompose(power)) { result = mul(result, power_of_power_of_2_mod(metapower)); } return result; } Note that O(log n) is, in practice, O(1) for ulong arguments (as log n < 63); and that this code is compatible with any uint MODULO (MODULO < 2^32), independent of whether MODULO is prime or not.
It can be solved in O((log n)^2). Try this approach:- unsigned long long int fastspcexp(unsigned long long int n) { if(n==0) return 1; if(n%2==0) return (((fastspcexp(n/2))*(fastspcexp(n/2)))%1000000007); else return ( ( ((fastspcexp(n/2)) * (fastspcexp(n/2)) * 2) %1000000007 ) ); } This is a recursive approach and is pretty fast enough to meet the time requirements in most of the programming competitions.
If u also want to store that array ie. (2^i)%mod [i=0 to whatever] than: long mod = 1000000007; long int pow_mod[ele]; //here 'ele' = maximum power upto which you want to store 2^i pow_mod[0]=1; //2^0 = 1 for(int i=1;i<ele;++i){ pow_mod[i] = (pow_mod[i-1]*2)%mod; } I hope it'll be helpful to someone.
How to add two numbers without using ++ or + or another arithmetic operator
How do I add two numbers without using ++ or + or any other arithmetic operator? It was a question asked a long time ago in some campus interview. Anyway, today someone asked a question regarding some bit-manipulations, and in answers a beautiful quide Stanford bit twiddling was referred. I spend some time studying it and thought that there actually might be an answer to the question. I don't know, I could not find one. Does an answer exist?
This is something I have written a while ago for fun. It uses a two's complement representation and implements addition using repeated shifts with a carry bit, implementing other operators mostly in terms of addition. #include <stdlib.h> /* atoi() */ #include <stdio.h> /* (f)printf */ #include <assert.h> /* assert() */ int add(int x, int y) { int carry = 0; int result = 0; int i; for(i = 0; i < 32; ++i) { int a = (x >> i) & 1; int b = (y >> i) & 1; result |= ((a ^ b) ^ carry) << i; carry = (a & b) | (b & carry) | (carry & a); } return result; } int negate(int x) { return add(~x, 1); } int subtract(int x, int y) { return add(x, negate(y)); } int is_even(int n) { return !(n & 1); } int divide_by_two(int n) { return n >> 1; } int multiply_by_two(int n) { return n << 1; } int multiply(int x, int y) { int result = 0; if(x < 0 && y < 0) { return multiply(negate(x), negate(y)); } if(x >= 0 && y < 0) { return multiply(y, x); } while(y > 0) { if(is_even(y)) { x = multiply_by_two(x); y = divide_by_two(y); } else { result = add(result, x); y = add(y, -1); } } return result; } int main(int argc, char **argv) { int from = -100, to = 100; int i, j; for(i = from; i <= to; ++i) { assert(0 - i == negate(i)); assert(((i % 2) == 0) == is_even(i)); assert(i * 2 == multiply_by_two(i)); if(is_even(i)) { assert(i / 2 == divide_by_two(i)); } } for(i = from; i <= to; ++i) { for(j = from; j <= to; ++j) { assert(i + j == add(i, j)); assert(i - j == subtract(i, j)); assert(i * j == multiply(i, j)); } } return 0; }
Or, rather than Jason's bitwise approach, you can calculate many bits in parallel - this should run much faster with large numbers. In each step figure out the carry part and the part that is sum. You attempt to add the carry to the sum, which could cause carry again - hence the loop. >>> def add(a, b): while a != 0: # v carry portion| v sum portion a, b = ((a & b) << 1), (a ^ b) print b, a return b when you add 1 and 3, both numbers have the 1 bit set, so the sum of that 1+1 carries. The next step you add 2 to 2 and that carries into the correct sum four. That causes an exit >>> add(1,3) 2 2 4 0 4 Or a more complex example >>> add(45, 291) 66 270 4 332 8 328 16 320 336 Edit: For it to work easily on signed numbers you need to introduce an upper limit on a and b >>> def add(a, b): while a != 0: # v carry portion| v sum portion a, b = ((a & b) << 1), (a ^ b) a &= 0xFFFFFFFF b &= 0xFFFFFFFF print b, a return b Try it on add(-1, 1) to see a single bit carry up through the entire range and overflow over 32 iterations 4294967294 2 4294967292 4 4294967288 8 ... 4294901760 65536 ... 2147483648 2147483648 0 0 0L
int Add(int a, int b) { while (b) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; }
You could transform an adder circuit into an algorithm. They only do bitwise operations =)
Well, to implement an equivalent with boolean operators is quite simple: you do a bit-by-bit sum (which is an XOR), with carry (which is an AND). Like this: int sum(int value1, int value2) { int result = 0; int carry = 0; for (int mask = 1; mask != 0; mask <<= 1) { int bit1 = value1 & mask; int bit2 = value2 & mask; result |= mask & (carry ^ bit1 ^ bit2); carry = ((bit1 & bit2) | (bit1 & carry) | (bit2 & carry)) << 1; } return result; }
You've already gotten a couple bit manipulation answers. Here's something different. In C, arr[ind] == *(arr + ind). This lets us do slightly confusing (but legal) things like int arr = { 3, 1, 4, 5 }; int val = 0[arr];. So we can define a custom add function (without explicit use of an arithmetic operator) thusly: unsigned int add(unsigned int const a, unsigned int const b) { /* this works b/c sizeof(char) == 1, by definition */ char * const aPtr = (char *)a; return (int) &(aPtr[b]); } Alternately, if we want to avoid this trick, and if by arithmetic operator they include |, &, and ^ (so direct bit manipulation is not allowed) , we can do it via lookup table: typedef unsigned char byte; const byte lut_add_mod_256[256][256] = { { 0, 1, 2, /*...*/, 255 }, { 1, 2, /*...*/, 255, 0 }, { 2, /*...*/, 255, 0, 1 }, /*...*/ { 254, 255, 0, 1, /*...*/, 253 }, { 255, 0, 1, /*...*/, 253, 254 }, }; const byte lut_add_carry_256[256][256] = { { 0, 0, 0, /*...*/, 0 }, { 0, 0, /*...*/, 0, 1 }, { 0, /*...*/, 0, 1, 1 }, /*...*/ { 0, 0, 1, /*...*/, 1 }, { 0, 1, 1, /*...*/, 1 }, }; void add_byte(byte const a, byte const b, byte * const sum, byte * const carry) { *sum = lut_add_mod_256[a][b]; *carry = lut_add_carry_256[a][b]; } unsigned int add(unsigned int a, unsigned int b) { unsigned int sum; unsigned int carry; byte * const aBytes = (byte *) &a; byte * const bBytes = (byte *) &b; byte * const sumBytes = (byte *) ∑ byte * const carryBytes = (byte *) &carry; byte const test[4] = { 0x12, 0x34, 0x56, 0x78 }; byte BYTE_0, BYTE_1, BYTE_2, BYTE_3; /* figure out endian-ness */ if (0x12345678 == *(unsigned int *)test) { BYTE_0 = 3; BYTE_1 = 2; BYTE_2 = 1; BYTE_3 = 0; } else { BYTE_0 = 0; BYTE_1 = 1; BYTE_2 = 2; BYTE_3 = 3; } /* assume 4 bytes to the unsigned int */ add_byte(aBytes[BYTE_0], bBytes[BYTE_0], &sumBytes[BYTE_0], &carryBytes[BYTE_0]); add_byte(aBytes[BYTE_1], bBytes[BYTE_1], &sumBytes[BYTE_1], &carryBytes[BYTE_1]); if (carryBytes[BYTE_0] == 1) { if (sumBytes[BYTE_1] == 255) { sumBytes[BYTE_1] = 0; carryBytes[BYTE_1] = 1; } else { add_byte(sumBytes[BYTE_1], 1, &sumBytes[BYTE_1], &carryBytes[BYTE_0]); } } add_byte(aBytes[BYTE_2], bBytes[BYTE_2], &sumBytes[BYTE_2], &carryBytes[BYTE_2]); if (carryBytes[BYTE_1] == 1) { if (sumBytes[BYTE_2] == 255) { sumBytes[BYTE_2] = 0; carryBytes[BYTE_2] = 1; } else { add_byte(sumBytes[BYTE_2], 1, &sumBytes[BYTE_2], &carryBytes[BYTE_1]); } } add_byte(aBytes[BYTE_3], bBytes[BYTE_3], &sumBytes[BYTE_3], &carryBytes[BYTE_3]); if (carryBytes[BYTE_2] == 1) { if (sumBytes[BYTE_3] == 255) { sumBytes[BYTE_3] = 0; carryBytes[BYTE_3] = 1; } else { add_byte(sumBytes[BYTE_3], 1, &sumBytes[BYTE_3], &carryBytes[BYTE_2]); } } return sum; }
All arithmetic operations decompose to bitwise operations to be implemented in electronics, using NAND, AND, OR, etc. gates. Adder composition can be seen here.
For unsigned numbers, use the same addition algorithm as you learned in first class, but for base 2 instead of base 10. Example for 3+2 (base 10), i.e 11+10 in base 2: 1 ‹--- carry bit 0 1 1 ‹--- first operand (3) + 0 1 0 ‹--- second operand (2) ------- 1 0 1 ‹--- total sum (calculated in three steps)
If you're feeling comedic, there's always this spectacularly awful approach for adding two (relatively small) unsigned integers. No arithmetic operators anywhere in your code. In C#: static uint JokeAdder(uint a, uint b) { string result = string.Format(string.Format("{{0,{0}}}{{1,{1}}}", a, b), null, null); return result.Length; } In C, using stdio (replace snprintf with _snprintf on Microsoft compilers): #include <stdio.h> unsigned int JokeAdder(unsigned int a, unsigned int b) { return snprintf(NULL, 0, "%*.*s%*.*s", a, a, "", b, b, ""); }
Here is a compact C solution. Sometimes recursion is more readable than loops. int add(int a, int b){ if (b == 0) return a; return add(a ^ b, (a & b) << 1); }
#include<stdio.h> int add(int x, int y) { int a, b; do { a = x & y; b = x ^ y; x = a << 1; y = b; } while (a); return b; } int main( void ){ printf( "2 + 3 = %d", add(2,3)); return 0; }
short int ripple_adder(short int a, short int b) { short int i, c, s, ai, bi; c = s = 0; for (i=0; i<16; i++) { ai = a & 1; bi = b & 1; s |= (((ai ^ bi)^c) << i); c = (ai & bi) | (c & (ai ^ bi)); a >>= 1; b >>= 1; } s |= (c << i); return s; }
## to add or subtract without using '+' and '-' ## #include<stdio.h> #include<conio.h> #include<process.h> void main() { int sub,a,b,carry,temp,c,d; clrscr(); printf("enter a and b:"); scanf("%d%d",&a,&b); c=a; d=b; while(b) { carry=a&b; a=a^b; b=carry<<1; } printf("add(%d,%d):%d\n",c,d,a); temp=~d+1; //take 2's complement of b and add it with a sub=c+temp; printf("diff(%d,%d):%d\n",c,d,temp); getch(); }
The following would work. x - (-y)
This can be done recursively: int add_without_arithm_recursively(int a, int b) { if (b == 0) return a; int sum = a ^ b; // add without carrying int carry = (a & b) << 1; // carry, but don’t add return add_without_arithm_recursively(sum, carry); // recurse } or iteratively: int add_without_arithm_iteratively(int a, int b) { int sum, carry; do { sum = a ^ b; // add without carrying carry = (a & b) << 1; // carry, but don’t add a = sum; b = carry; } while (b != 0); return a; }
Code to implement add,multiplication without using +,* operator; for subtraction pass 1's complement +1 of number to add function #include<stdio.h> unsigned int add(unsigned int x,unsigned int y) { int carry=0; while (y != 0) { carry = x & y; x = x ^ y; y = carry << 1; } return x; } int multiply(int a,int b) { int res=0; int i=0; int large= a>b ? a :b ; int small= a<b ? a :b ; for(i=0;i<small;i++) { res = add(large,res); } return res; } int main() { printf("Sum :: %u,Multiply is :: %d",add(7,15),multiply(111,111)); return 0; }
The question asks how to add two numbers so I don't understand why all the solutions offers the addition of two integers? What if the two numbers were floats i.e. 2.3 + 1.8 are they also not considered numbers? Either the question needs to be revised or the answers. For floats I believe the numbers should be broken into their components i.e. 2.3 = 2 + 0.3 then the 0.3 should be converted to an integer representation by multiplying with its exponent factor i.e 0.3 = 3 * 10^-1 do the same for the other number and then add the integer segment using one of the bit shift methods given as a solution above handling situations for carry over to the unit digits location i.e. 2.7 + 3.3 = 6.0 = 2+3+0.7+0.3 = 2 + 3 + 7x10^-1 + 3x10^-1 = 2 + 3 + 10^10^-1 (this can be handled as two separate additions 2+3=5 and then 5+1=6)
With given answers above, it can be done in single line code: int add(int a, int b) { return (b == 0) ? a : add(a ^ b, (a & b) << 1); }
You can use double negetive to add two integers for example: int sum2(int a, int b){ return -(-a-b); }
Without using any operators adding two integers can be done in different ways as follows: int sum_of_2 (int a, int b){ int sum=0, carry=sum; sum =a^b; carry = (a&b)<<1; return (b==0)? a: sum_of_2(sum, carry); } // Or you can just do it in one line as follows: int sum_of_2 (int a, int b){ return (b==0)? a: sum_of_2(a^b, (a&b)<<1); } // OR you can use the while loop instead of recursion function as follows int sum_of_2 (int a, int b){ if(b==0){ return a; } while(b!=0){ int sum = a^b; int carry = (a&b)<<1; a= sum; b=carry; } return a; }
int add_without_arithmatic(int a, int b) { int sum; char *p; p = (char *)a; sum = (int)&p[b]; printf("\nSum : %d",sum); }