开发者

how can i implement iterative version Logn base to power?

开发者 https://www.devze.com 2023-01-27 04:46 出处:网络
#include<stdio.h> int powFast(int b, int e){ if(e==1){ return b; } else if(e%2 ==0){ return powFast(b,e/2)*powFast(b,e/2);
#include<stdio.h>

int powFast(int b, int e){
    if(e==1){
      return b;
      }
    else if(e%2 ==0){
         return powFast(b,e/2)*powFast(b,e/2);
         }
    else
           {
        return po开发者_开发技巧wFast(b,e-1)*powFast(b,1);
        }
}

main() {
int base,exp,ans;

         printf("\n\n\n\n\t\tPlease enter a number:");
         scanf("\n%d",&base);
         printf("\t\tTo what power would you like it raised?:");
         scanf("\n%d",&exp);
         ans = powFast(base, exp);
         printf("\n\t\t\%d to the power of %d is: %d",base,exp,ans);
         main();
         getch();
 }


int powFast(int b, int e) {
    int p = 1;   
    while (e > 0) {
        if(e%2 != 0) {
            p = p*b;  
        } 
        e = e / 2;
        b = b * b;
    }
    return p;
}

No explanation, deliberately. If it's an assignment, please edit your question to say so and I'll edit this one to explain

0

精彩评论

暂无评论...
验证码 换一张
取 消