C說話求冪盤算的高效解法。本站提示廣大學習愛好者:(C說話求冪盤算的高效解法)文章只能為提供參考,不一定能成為您想要的結果。以下是C說話求冪盤算的高效解法正文
本文實例演示了C說話求冪盤算的高效解法。很有適用價值。分享給年夜家供年夜家參考。詳細辦法以下:
標題以下:
給定base,求base的冪exp
只斟酌根本功效,不做任何界限前提的剖斷,可以獲得以下代碼:
#include <iostream> using namespace std; int cacExp(int base, int exp) { int result = 1; int theBase = 1; while (exp) { if (exp & 0x01) result = result * base; base = base * base; exp = exp >> 1; } return result; } int getRecurExp(int base, int exp) { if (exp == 0) { return 1; } if (exp == 1) { return base; } int result = getRecurExp(base, exp >> 1); result *= result; if (exp & 0x01) result *= base; return result; } int main() { for (int i = 1; i < 10; i++) { int result = cacExp(2, i); //int result = getRecurExp(2, i); cout << "result: " << result << endl; } return 0; }
再來看看數值的整數次方求解辦法:
#include <iostream> using namespace std; bool equalZero(double number) { if (number < 0.000001 && number > -0.000001) return true; else return false; } double _myPow(double base, int exp) { if (exp == 0) return 1; if (exp == 1) return base; double result = _myPow(base, exp >> 1); result *= result; if (exp & 0x01) result *= base; return result; } double _myPow2(double base, int exp) { if (exp == 0) return 1; double result = 1; while (exp) { if (exp & 0x01) result *= base; base *= base; exp = exp >> 1; } return result; } double myPow(double base, int exp) { if (equalZero(base)) return 0; if (exp == 0) return 1; bool flag = false; if (exp < 0) { flag = true; exp = -exp; } double result = _myPow2(base, exp); if (flag) { result = 1 / result; } return result; } void main() { double base = 2.0; int exp = -5; double result = myPow(base, exp); cout << "result: " << result << endl; }
信任本文所述對年夜家C法式算法設計的進修有必定的自創價值。