code_junkie

The most efficient way to implement an integer based power function pow(int, int)

Nov 11th, 2011
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. // 2^3
  2. pow(2,3) == 8
  3.  
  4. // 5^5
  5. pow(5,5) == 3125
  6.  
  7. int ipow(int base, int exp)
  8. {
  9. int result = 1;
  10. while (exp)
  11. {
  12. if (exp & 1)
  13. result *= base;
  14. exp >>= 1;
  15. base *= base;
  16. }
  17.  
  18. return result;
  19. }
  20.  
  21. x^15 = (x^7)*(x^7)*x
  22. x^7 = (x^3)*(x^3)*x
  23. x^3 = x*x*x
  24.  
  25. n*n = n^2
  26. n^2*n = n^3
  27. n^3*n^3 = n^6
  28. n^6*n^6 = n^12
  29. n^12*n^3 = n^15
  30.  
  31. struct IeeeFloat
  32. {
  33.  
  34. unsigned int base : 23;
  35. unsigned int exponent : 8;
  36. unsigned int signBit : 1;
  37. };
  38.  
  39.  
  40. union IeeeFloatUnion
  41. {
  42. IeeeFloat brokenOut;
  43. float f;
  44. };
  45.  
  46. inline float twoToThe(char exponent)
  47. {
  48. // notice how the range checking is already done on the exponent var
  49. static IeeeFloatUnion u;
  50. u.f = 2.0;
  51. // Change the exponent part of the float
  52. u.brokenOut.exponent += (exponent - 1);
  53. return (u.f);
  54. }
  55.  
  56. 2 ** 3 == 1 << 3 == 8
  57. 2 ** 30 == 1 << 30 == 1073741824 (A Gigabyte)
  58.  
  59. int pow( int base, int exponent)
  60. {
  61. if (exponent == 0) return 1; // base case;
  62. int temp = pow(base, exponent/2);
  63. if (exponent % 2 == 0)
  64. return temp * temp;
  65. else
  66. return (base * temp * temp);
  67. }
  68.  
  69. int pow(int base, int pow) {
  70. int res = 1;
  71. for(int i=pow; i<pow; i++)
  72. res *= base;
  73.  
  74. return res;
  75. }
Add Comment
Please, Sign In to add comment