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.4k
- Engineering Mathematics 5.9k
- Digital Logic 2.3k
- Programming & DS 4.3k
- Algorithms 3.7k
- Theory of Computation 4.6k
- Compiler Design 1.7k
- Databases 3.4k
- CO & Architecture 2.9k
- Computer Networks 3.4k
- Non GATE 1.2k
- Others 1.3k
- Admissions 506
- Exam Queries 482
- Tier 1 Placement Questions 22
- Job Queries 64
- Projects 15

40,903 questions

47,558 answers

146,289 comments

62,306 users