Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int multiplication(int num1, int num2);
- int multiplication_loop(int num1, int num2, int tmp);
- // Multiplication function
- int multiplication(int num1, int num2) {
- return multiplication_loop(num1, num2, 0);
- }
- // recursive function that calculate multiplication
- // The tmp variable's value is the count of bit of num2 currently being calculated.
- int multiplication_loop(int num1, int num2, int tmp) {
- // Integer is 32bit.
- if(tmp == 32)
- return 0;
- // if current bit of num2 is 1, add the value that shifts num1 variable and tmp variable.
- return ((num2 & 1) ? num1 << tmp : 0) + multiplication_loop(num1, num2 >> 1, tmp + 1);
- }
- int main() {
- printf("%d", multiplication(10, 5));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement