Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- multiplication_with_shift_operator_v1.c
- https://www.geeksforgeeks.org/multiplication-two-numbers-shift-operator/
- https://www.geeksforgeeks.org/left-shift-right-shift-operators-c-cpp/
- How the C/C++ << and >> Shift Operators Work
- https://www.eeweb.com/profile/max-maxfield/articles/how-the-c-c-shift-operators-work
- Left shifting an integer “x” with an integer “y” (x<<y)
- is equivalent to multiplying x with 2^y (2 raise to power y).
- Similarly right shifting (x>>y) is equivalent to dividing x with 2^y.
- The Joyful Programmer:
- Old optimization statement that I learned many, many, many
- years ago, when reading an optimization book by Michael Abrash. It goes:
- "Multiply if you must, but never divide."
- Remove the multiplication operator. Why? Well,
- when C++ is reduced to machine language, it takes the processor (newer ones)
- about 30 clock cycles to execute a single multiplication. Division takes over
- 60 clock cycles. However, we can reduce the amount of clock cycles by using a
- shift operator.
- That's only 2 clock cycles versus an estimated 30 clock cycles, a 28 clock
- cycle difference, which could be essential if you are doing millions of
- calculations.
- There are also opposing opinions:
- Is multiplication and division using shift operators in C actually faster?
- This depends on the processor and the compiler. Some compilers already
- optimize code this way, others don't. So you need to check each time
- your code needs to be optimized this way.
- https://stackoverflow.com/questions/6357038/is-multiplication-and-division-using-shift-operators-in-c-actually-faster
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- int multiply(int n, int m)
- {
- int ans = 0, count = 0;
- while (m)
- {
- if (m % 2 == 1) // check for set bit and left
- ans += n << count; // shift n, count times
- count++; // increment of place value (count)
- m /= 2;
- }
- return ans;
- }
- int main(void)
- {
- int n = 20 , m = 13;
- printf("\n %d * %d = %d \n", n, m, multiply(n, m) );
- return 0;
- } // main()
Add Comment
Please, Sign In to add comment