Guest User

Untitled

a guest
Oct 22nd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. #include<iostream>
  2. #include<cmath>
  3. using namespace std;
  4.  
  5. int fast_exponentiation(int base, int pow) {
  6. unsigned int result; // variable to store intermediaries
  7.  
  8. if (pow == 1) {
  9. return base;
  10. }
  11. else if (pow == 0) {
  12. return 1;
  13. }
  14.  
  15. result = fast_exponentiation(base, floor(pow/2));
  16.  
  17. // even power
  18. if (pow % 2 == 0) {
  19. return result * result;
  20. }
  21. // odd power
  22. else {
  23. return result * base * result;
  24. }
  25. }
  26.  
  27. int main() {
  28. int num, answer, p;
  29. cout << "Enter the base: ";
  30. cin >> num;
  31.  
  32. cout << "Enter power: ";
  33. cin >> p;
  34.  
  35. answer = fast_exponentiation(num, p);
  36. cout << answer << endl;
  37.  
  38. return 0;
  39. }
Add Comment
Please, Sign In to add comment