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

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

问题描述

在 C 中给出一个整数的另一个整数的幂的最有效方法是什么?

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

推荐答案

平方取幂.

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

    return result;
}

这是在非对称密码学中对大数进行模幂运算的标准方法.

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

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

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