Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int multiplication(int num1, int num2);
  4. int multiplication_loop(int num1, int num2, int tmp);
  5.  
  6. // Multiplication function
  7. int multiplication(int num1, int num2) {
  8. return multiplication_loop(num1, num2, 0);
  9. }
  10.  
  11. // recursive function that calculate multiplication
  12. // The tmp variable's value is the count of bit of num2 currently being calculated.
  13. int multiplication_loop(int num1, int num2, int tmp) {
  14. // Integer is 32bit.
  15. if(tmp == 32)
  16. return 0;
  17. // if current bit of num2 is 1, add the value that shifts num1 variable and tmp variable.
  18. return ((num2 & 1) ? num1 << tmp : 0) + multiplication_loop(num1, num2 >> 1, tmp + 1);
  19. }
  20.  
  21. int main() {
  22. printf("%d", multiplication(10, 5));
  23. return 0;
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement