code_junkie

What's the fastest way to divide an integer by 3?

Nov 11th, 2011
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. int x = n / 3; // <-- make this faster
  2.  
  3. // for instance
  4.  
  5. int a = n * 3; // <-- normal integer multiplication
  6.  
  7. int b = (n << 1) + n; // <-- potentially faster multiplication
  8.  
  9. int a;
  10. int b;
  11.  
  12. a = some value;
  13. b = a / 3;
  14.  
  15. y = x / 3
  16.  
  17. y = x / 3
  18.  
  19. static inline uint32_t divby3 (
  20. uint32_t divideMe
  21. ) {
  22. return (uint32_t)(((uint64_t)0xAAAAAAABULL * divideMe) >> 33);
  23. }
  24.  
  25. #include <stdio.h>
  26.  
  27. void main()
  28. {
  29. int n = 1000;
  30. int a,b;
  31. a = n >> 2;
  32. b = (a >> 2);
  33. a += b;
  34. b = (b >> 2);
  35. a += b;
  36. b = (b >> 2);
  37. a += b;
  38. b = (b >> 2);
  39. a += b;
  40. printf("a=%dn", a);
  41. }
  42.  
  43. int x = n * 0.33333333333333333333333333333333;
  44.  
  45. int x = n >> 2; // divide by 4
Add Comment
Please, Sign In to add comment