The Gateway to Computer Science Excellence

First time here? Checkout the FAQ!

x

+4 votes

Best answer

I guess you meant multiplication and division by power of 2. For multiplication your question answers itself, as answer is always an integer. For division, answer to your question is "yes"- it won't work. Because when we use shift instead of division, compiler will just use shift instruction provided by the CPU (if it does). So, lets take Intel architecture and this is what Intel manual says for SAR (Shift Arithmetic Right) Instruction.

"Using the SAR instruction to perform a division operation does not produce the same result as the IDIV instruction.

The quotient from the IDIV instruction is rounded toward zero, whereas the “quotient” of the SAR instruction is

rounded toward negative infinity. This difference is apparent only for negative numbers. For example, when the

IDIV instruction is used to divide -9 by 4, the result is -2 with a remainder of -1. If the SAR instruction is used to

shift -9 right by two bits, the result is -3 and the “remainder” is +3; however, the SAR instruction stores only the

most significant bit of the remainder (in the CF flag)"

So, for positive numbers, when we want only the quotient we can safely use shift in place of division by power of 2. Otherwise we should not use shift.

- All categories
- General Aptitude 1.3k
- Engineering Mathematics 5.2k
- Digital Logic 2k
- Programming & DS 3.7k
- Algorithms 3.2k
- Theory of Computation 4k
- Compiler Design 1.6k
- Databases 3k
- CO & Architecture 2.6k
- Computer Networks 3k
- Non GATE 1k
- Others 1.3k
- Admissions 488
- Exam Queries 436
- Tier 1 Placement Questions 18
- Job Queries 56
- Projects 9

36,203 questions

43,662 answers

124,117 comments

42,947 users