实现一个基于整数次幂函数战俘的最有效方式(INT,INT) [英] The most efficient way to implement an integer based power function pow(int, int)

查看:131
本文介绍了实现一个基于整数次幂函数战俘的最有效方式(INT,INT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是给提高一个整数的另一个整数权力在C最有效的方法是什么?

  // 2 ^ 3
POW(2,3)== 8

// 5 ^ 5
POW(5,5)== 3125
 

解决方案

幂的平方。

  INT ipow(INT基地,INT EXP)
{
    INT结果= 1;
    而(实验)
    {
        如果(预期&安培; 1)
            结果* =基地;
        EXP>> = 1;
        基地* =基地;
    }

    返回结果;
}
 

这是做模指数为庞大的数字在非对称加密的标准方法。

What is the most efficient way given to raise an integer to the power of another integer in C?

// 2^3
pow(2,3) == 8

// 5^5
pow(5,5) == 3125

解决方案

Exponentiation by squaring.

int ipow(int base, int exp)
{
    int result = 1;
    while (exp)
    {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }

    return result;
}

This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.

这篇关于实现一个基于整数次幂函数战俘的最有效方式(INT,INT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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