简体   繁体   English

C平方求幂的实现

[英]C implementation of exponentiation by squaring

I tried to implement the "exponentiation by squareing" algorithmn in C but my program has an odd behaviour. 我试图在C语言中实现“平方求幂”算法,但是我的程序表现出奇怪的现象。 First, here is a small code snippet: 首先,这是一个小代码段:

long long fast_power_1(long long base, long long power){
    long long result = 1;
    while (power > 0)
    {
        if (power % 2 == 0)
        {
            power = power / 2;
            base = base * base;
        }
        else
        {
            power = power - 1;
            result = (result*base);
            power = power / 2;
            base = (base * base);
        }
    }
return result;}

If I call the function with: 如果我通过以下方式调用该函数:

printf("%d\n",fast_power_1(2,100));

I expect the output to be something like 976371285, but the result is 0 and i don't quite understand why. 我期望输出类似于976371285,但结果为0,我不太清楚为什么。

long long should be printed using %lld format specifier otherwise it's Undefined Behavior. long long应该使用%lld格式说明符进行打印,否则为“未定义行为”。 Also this method already has overflow within for large values of power - because long long cant hold 2^100 (as of now in 32 or 64 bit systems- when it is 128 bit system of course it can). 同样,此方法对于较大的power值已经存在溢出-因为长时间不能保持2^100 (到目前为止,在3264位系统中-当然可以,如果是128位系统)。

As of now in your code if you provide not too large value of the exponent and use printf("%lld",..) then it would give you a valid result. 到目前为止,如果您提供的指数值不太大并使用printf("%lld",..)那么它将为您提供有效的结果。

Maybe you wanted to have modular arithmetic with it. 也许您想使用它的模块化算法。 (In general requirements stop at that - like modulo some large prime ie, 10^9+7 ). (一般要求就此停止-像对一些大质数取模,即10^9+7 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM