C語言求冪計算的高效解法
更新時間:2014年09月18日 09:07:53 投稿:shichen2014
這篇文章主要介紹了C語言求冪計算的高效解法,分別演示了求冪運算與整數(shù)次方的解法,具有不錯的參考借鑒價值,需要的朋友可以參考下
本文實例演示了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;
}
再來看看數(shù)值的整數(shù)次方求解方法:
#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程序算法設(shè)計的學(xué)習(xí)有一定的借鑒價值。
相關(guān)文章
C++運行時獲取類型信息的type_info類與bad_typeid異常
這篇文章主要介紹了C++運行時獲取類型信息的type_info類與bad_typeid異常,是C++入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2016-01-01
C++ opencv ffmpeg圖片序列化實現(xiàn)代碼解析
這篇文章主要介紹了C++ opencv ffmpeg圖片序列化實現(xiàn)代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
C語言詳細分析講解關(guān)鍵字enum與sizeof及typedef的用法
在?C?語言中經(jīng)常會見到?enum、sizeof、typedef,那么我們今天就來講解下它們?nèi)齻€,enum是C語言中的一種自定義類型,它是一種枚舉類型,sizeof是編譯器的內(nèi)置指示符,用于計算類型或變量所占內(nèi)存打小,typedef用于給一個已經(jīng)存在的數(shù)據(jù)類型重命名,本質(zhì)上不能產(chǎn)生新的類型2022-04-04
C++設(shè)計模式編程之Flyweight享元模式結(jié)構(gòu)詳解
這篇文章主要介紹了C++設(shè)計模式編程的Flyweight享元模式結(jié)構(gòu),享元模式在實現(xiàn)過程中主要是要為共享對象提供一個存放的"倉庫"(對象池),需要的朋友可以參考下2016-03-03

