数值的整数次方——11

本文介绍了一种快速幂运算的方法,并通过优化循环次数提高效率。利用二进制位操作,将传统循环相乘的方式改进为递归方式,显著降低了时间复杂度。

   实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。


    首先可以想到的是,如果exponent是个大于零的数,可用循环来进行相乘,而如果exponent是个复数,依然可以将base进行相乘,最后再取其倒数也就是用1去除以相乘结果。程序设计如下:

#include <iostream>#include <math.h>using namespace std;double my_pow(double base, int exp){    if(exp == 0)//当exp为0的时候,不论base为多少结果都为1        return 1;    if((base == 0) || (base == 1))//当base为0或者1的时候不论exp为多少结果都为base        return base;    double ret = 1.0;    int flag = 1;//设定标志位,判断exp的正负性    if(exp < 0)    {        flag = 0;        exp *= (-1);    }    while(exp--)    {        ret *= base;    }    if(flag == 0)        ret = 1/ret;    return ret;}int main(){    double base = 6.123784;    int exp = -5;    double ret = my_pow(base, exp);    cout<<"my_pow ret: "<<ret<<endl;    cout<<"pow ret: "<<pow(base, exp)<<endl;    return 0;}


上面的栗子中,为了验证结果的正确性与否在输出结果的比较中调用了库函数的pow来进行比较,运行程序得结果:

wKioL1cvBoiRrR3rAAAQ1TQ1Kg0366.png


    但是上面的代码还是有可优化的成分的,比如如果exp的值比较大,那么循环的次数也就比较多,这个时间复杂度就为O(N),如果exp的值为100的话,那么其实,当循环乘到50的时候,只需要再乘上一个50就能得到结果,而不需要再循环50次,而50又可以由相乘25次的结果再自乘一次得到,而25次的结果又可以由12次的结果乘以自身再乘一个base而得到......因此,将上面的代码改为如下:

double GetPow(double base, int exp){    double ret = 1;    if(exp != 0)    {           ret = GetPow(base, exp>>1);        if((exp & 0x1) == 0)        {            ret *= ret;        }        else        {            ret *= (ret * base);        }       }       return ret;}double my_pow(double base, int exp){     if((base == 0) || (base == 1))         return base;    int flag = 1;    if(exp < 0)    {           flag = 0;        exp *= (-1);    }       double ret = GetPow(base, exp);    if(flag == 0)        ret = 1/ret;    return ret;}


解释一下上面的GetPow函数,因为前面说可以将循环次数减少,比如100次方可以求50次方再平方,50次方可以求25次方再平方......以此类推,其实就是100->50->25->12(+1)->6->3->1(+1)->0,而我们从最低位倒着算起,base的0次方->base的1次方->base的3次方->base的6次方->base的12次方->......这样可以发现,其实就是在exponent的二进制表示位上进行的操作,从最高位到最低位,当比特位值为1时,就将前面的结果相乘再乘上一个base也就是上面的(+1),如果比特位值为0,就直接将前面的结果相乘......而从高位到低位就需要用递归来获取;

运行程序,结果和pow库函数相同。



《完》

本文出自 “敲完代码好睡觉zzz” 博客,请务必保留此出处http://2627lounuo.blog.51cto.com/10696599/1771568

### C语言实现大非负数指数运算 在C语言中,由于其本身不支持像Python那样的内置大数据类型或者像C++那样方便的模板机制,因此要实现大非负数的大非负数次方运算需要手动管理内存并定义自己的数据结构来存储这些超大规模数值。以下是基于双向链表存储大数并通过自定义函数模拟加法、乘法和幂运算的方法。 #### 数据结构设计 为了高效地表示大数,可以采用双向链表作为底层存储结构。每个节点保存一位十进制数字(0~9),这样便于逐位计算。对于指数运算来说,主要依赖于反复调用乘法操作。 ```c #include <stdio.h> #include <stdlib.h> typedef struct Node { int digit; // 单个数字 (0-9) struct Node* next; struct Node* prev; } Node; typedef struct BigInt { Node* head; // 链表头指针 Node* tail; // 链表尾指针 } BigInt; // 初始化BigInt对象 void initBigInt(BigInt* num) { num->head = NULL; num->tail = NULL; } // 向BigInt追加单个数字到末尾 void appendDigit(BigInt* num, int d) { Node* newNode = malloc(sizeof(Node)); newNode->digit = d; newNode->next = NULL; newNode->prev = num->tail; if (!num->tail) { num->head = newNode; } else { num->tail->next = newNode; } num->tail = newNode; } ``` #### 基本运算实现 ##### 加法 两个大数相加可以通过从最低有效位开始逐步累加的方式完成,并考虑进位情况。 ```c BigInt addBigInt(const BigInt* a, const BigInt* b) { BigInt result; initBigInt(&result); Node* pa = a->head; Node* pb = b->head; int carry = 0; while (pa || pb || carry) { int sum = carry; if (pa) { sum += pa->digit; pa = pa->next;} if (pb) { sum += pb->digit; pb = pb->next;} appendDigit(&result, sum % 10); carry = sum / 10; } return result; } ``` ##### 乘法 乘法规则类似于手写竖式方法,需遍历每一位并与另一个数体相乘后再错位叠加最终结果。 ```c BigInt multiplyBySingleDigit(const BigInt* baseNum, int multiplier){ BigInt product; initBigInt(&product); Node* current = baseNum->head; int carry=0; while(current||carry>0){ long total=(current ? current->digit : 0)*multiplier + carry; appendDigit(&product,(int)(total%10)); carry=total/10; if(current){current=current->next;} } return product; } BigInt multiplyBigInts(const BigInt* multiplicand,const BigInt* multiplier){ BigInt finalProduct; initBigInt(&finalProduct); Node* multPtr=multiplier->head; int shiftCount=0; while(multPtr!=NULL){ BigInt tempProd=multiplyBySingleDigit(multiplicand,multPtr->digit); for(int i=0;i<shiftCount;i++)appendDigit(&tempProd,0); finalProduct=addBigInt(&finalProduct,&tempProd); free(tempProd.head); multPtr=multPtr->next; ++shiftCount; } return finalProduct; } ``` ##### 幂运算 利用快速幂算法减少不必要的重复计算次数,从而提高效率。 ```c BigInt powerBigInt(const BigInt* base,int exponent){ BigInt one; initBigInt(&one); appendDigit(&one,1); BigInt res=*base; int expCopy=exponent; while(expCopy>1){ if((expCopy&1)==1){ res=multiplyBigInts(&res,base); } *base=multiplyBigInts(base,base); expCopy>>=1; } if(exponent==0)return one; else return res; } ``` 以上展示了如何构建一个简单的系统来进行大数的基本四则运算及其扩展应用——幂运算[^1]。值得注意的是,在实际开发过程中还需要加入更多的边界条件判断以及优化措施以提升健壮性和执行速度。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值