C : x to the power n using repeated squaring without recursive function

标签 c

<分区>

这是我的代码,它计算 2 的 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 等等

最佳答案

我怀疑你在找exponentiation by squaring是这样的:

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 to the power n using repeated squaring without recursive function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23079443/

相关文章:

android - CheckJNI 选项不起作用

c - 从 C 中的字符串中提取网址

c程序输出说明

c++ - Igraph (C) 返回错误的顶点 ID

c - 将 3D 数组作为参数传递给 C 中的函数

c - 在一个条件下混合赋值和 free()?

c++ - 如何修复闪烁的 LED 矩阵和液晶菜单屏幕

ios - iOS 应用程序中的 C 样式字符串被损坏

CMake:如何从命令行指定在何处查找本地安装的库

c - 如何在 C 中使用正则表达式?