【笔记】如何理解快速幂?

常规求幂:时间复杂度O(n)

求: x n x^{n} xn

int remainder(int x, int n)
{
    
    
	long long res = 1;
	while (n)
	{
    
    
		res = res * x % mod;	//这里取模是为了防止大数溢出
		n--;
	}
	return res;
}

下面引出二分求余法计算,可以把时间降至O(logn)

快速幂

n为偶数: x n = ( x 2 ) n / 2 x^{n} = (x^2)^{n/2} xn=(x2)n/2
n为奇数: x n = ( x 2 ) n / 2 ∗ x x^{n} = (x^2)^{n/2}*x xn=(x2)n/2x
因此每次循环都将 a 的问题降至 a / 2的问题,时间复杂度O(logn)
在这里插入图片描述

int remainder(long long x, int n)
    {
    
    
        long long res = 1;
        while (n)
        {
    
    
            if (n & 1)  // 若n为奇数,则需要乘单独的x
            {
    
    
                res = res * x % mod;
            }
            x = x * x % mod;
            n /= 2;
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/qq_45691748/article/details/111702558