Java教程

快速幂

本文主要是介绍快速幂,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

快速幂

定义

就是把一个高次的数转换成很多低次累乘的形式,类似进制转换的原理。

优点

我们计算\(A^n\)的朴素的方法就是循环\(n\)次来求幂,这样便得到\(O(n)\)时间复杂度的方法,其实大家都想得到一种优化的方法即\(A^n=A^{\frac{n}{2}}*A^{\frac{n}{2}}\)。

一直递归下去,其间就可以省略很多不必要的计算,得到\(O(logn)\)的方法。

写法

#include<bits/stdc++.h>
#define int long long 
using namespace std;

//常规求幂
int pow1(int a, int b)
{
   int r = 1;
   while (b--)
   {
        r *= a;
   } 
   return r;
} 

//一般
int pow2(int a, int b)
{
    int r = 1, base = a;
    while (b != 0)
    {
        if (b % 2) 
        {
            r *= base;  
        }
        base *= base;
        b /= 2;
    }
    return r;
}

//位运算
int pow3(int x, int n)
{
    if (n == 0)
    {
        return 1;
    } 
    int t = 1;
    while (n != 0)
    {
        if(n & 1) 
        {
            t *= x;
        }
        n >>= 1;
        x *= x;
    }
    return t;
}

//递归
int pow4(int m, int n)
{
    if (n == 1) 
    {
        return m;   
    }
    int temp = pow4(m, n / 2);
    return (n % 2 == 0 ? 1 : m) * temp * temp;
}

signed main(unsigned)
{
	int a, b;
	cin >> a >> b;
	cout << pow1(a, b) << endl;
	cout << pow2(a, b) << endl;
	cout << pow3(a, b) << endl;
	cout << pow4(a, b) << endl;
	return 0; 
}
这篇关于快速幂的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!