code_junkie

Russian Peasant Multiplication

Nov 12th, 2011
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
  2.  
  3. int peasant_mult (int a, int b) {
  4. for (p = 0;
  5. p += (a & 1) * b, a != 1;
  6. a /= 2, b *= 2);
  7. return p;}
  8.  
  9.  
  10. See? Now it's clear how the three parts of the for
  11.  
  12. int sum = 0;
  13. while(1)
  14. {
  15. sum += (a & 1) * b;
  16. if(a == 1)
  17. break;
  18.  
  19. a = a / 2;
  20. b = b * 2;
  21. }
  22.  
  23. int sum = 0;
  24. while(1)
  25. {
  26. sum += (a & 1) * b;
  27. if(a == 1)
  28. break;
  29.  
  30. a = a / 2;
  31. b = b * 2;
  32. }
  33.  
  34. p = a * b;
  35.  
  36. for(p=0;p+=(-(a&1))&b,a!=1;a>>=1,b<<=1);
  37.  
  38. // Russian Peasant Multiplication ( p <- a*b, only works when a>0, b>0 )
  39. // See http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication
  40. for( p=0; p+=(a&1)*b, a!=1; a>>=1,b<<=1 );
  41.  
  42. int RussianPeasant(int a, int b)
  43. {
  44. // sum = a * b
  45. int sum = 0;
  46. while (a != 0)
  47. {
  48. if ((a & 1) != 0)
  49. sum += b;
  50. b <<= 1;
  51. a >>= 1;
  52. }
  53. return sum;
  54. }
  55.  
  56. function RPM(int a, int b){
  57. int rtn;
  58. for(rtn=0;rtn+=(a&1)*b,a!=1;a>>=1,b<<=1);
  59. return rtn;
  60. }
Add Comment
Please, Sign In to add comment