Advertisement
Guest User

x^n

a guest
Sep 10th, 2012
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.43 KB | None | 0 0
  1. #include <cstdio>
  2.  
  3. //x^n evaluation
  4. int main() {
  5.   double x = -10;
  6.   int n = 10;
  7.  
  8.  
  9.   int bc_n = n; //Save n for correct output;
  10.   bool invert = (n < 0);
  11.   if (invert) {
  12.     n = -n;
  13.   }
  14.  
  15.   double res = 1;
  16.   double pw = x;
  17.  
  18.  
  19.   while (n) {
  20.     if (n & 1) res *= pw;
  21.     pw *= pw;
  22.     n >>= 1;
  23.   }
  24.  
  25.   if (invert) {
  26.     res = 1 / res;
  27.     n = -n;
  28.   }
  29.  
  30.   printf("%lf^%d = %lf\n", x, bc_n, res);
  31.  
  32.   return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement