I found an interesting question on the internet...

An interviewer asked a programmer "How would you divide without using division or multiplication?" And the programmer came up with some weird bit shifting operation that did the division.

Now, I'd like to make a program that does something similar, since--

int a = 10;
a = a << 3

means 10 * (2^3)

and

a = 10
a = a >> 3

means 10 / (2^3)

--but I'd like to redefine the right operation (the 2 to the power of (arg) ) with an object from the bitset<N> class so that when a user does something like this..

bitset<4> bSet;
int a = 10;

for(int i = 0; i < 3; i++)
bSet.set(i); //should set the first 3 bits to 1, for 0111 or 2^2 + 2^1 + 2^0 = 7

a = a >> bSet;

... and perform 10 / 7 division.

I have an idea of how I should do this...

//somewhere in the operator overload command--

return arg1 / pow(2, log(arg2.to_ulong())/log(2));

--the question, though it may seem trivial, is how do I make this operator function overload the natural bitshifting operation for these operations? In short, where is the bitshifting defined exactly? I heard that << and >> respectively were cout and cin objects operators, but if they can be used for pure bitshifting then I doubt they'd be restricted to those classes.

Recommended Answers

All 2 Replies

I found an interesting question on the internet...
An interviewer asked a programmer "How would you divide without using division or multiplication?"

Division is repeated subtraction.
6/3 = 2.
3 can be subtracted from 6 twice, until you're left with zero. Which explains why dividing by 0 is infinity.
Multiplication is simply repeated addition.
Some old CPU's had no instructions for division and multiplication so people had to multiply/divide that way.

Division is repeated subtraction.
6/3 = 2.
3 can be subtracted from 6 twice, until you're left with zero. Which explains why dividing by 0 is infinity.
Multiplication is simply repeated addition.
Some old CPU's had no instructions for division and multiplication so people had to multiply/divide that way.

That's genius =)

I'll definitely have to remember that XD

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.