C:X到n次幂反复使用无平方递归函数 [英] C : x to the power n using repeated squaring without recursive function

查看:107
本文介绍了C:X到n次幂反复使用无平方递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code将其计算2次幂16

here is my code it calculate 2 raised to the power 16

#include<stdio.h>
#include<math.h>

int main()
{
    int i;
    long int x=2;
    int n=16;
    int k=log(n)/log(2);
    for(i=1;i<=k;i++)
    {
        x=x*x;
    }
    printf("%d",x);
    printf("\n%d",k);
}

我想计算此当x即n的功率不是2.如权力。说N = 19,N = 43等

i want to calculate this when the power of x i.e. n is not the power of 2. for eg. say n=19,n=43 etc

推荐答案

我怀疑你正在寻找幂通过平方这是这样的:

I suspect that you are looking for exponentiation by squaring which goes like this:

unsigned int intpow(unsigned int base, unsigned int exponent)
{
    unsigned int result = 1;
    while (exponent > 0)
    {
        while ((exponent & 1) == 0)
        {
            exponent /= 2;
            base *= base;
        }
        exponent--;
        result *= base;
    }
    return result;
}

这篇关于C:X到n次幂反复使用无平方递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆