使用快速幂运算将A的升高值计算为B的幂

Now here we are going to learn that how to compute the value of a^b i.e. "A" raise to the power "B" using an optimized algorithm called as "fast-exponentiation"?

现在,我们将在这里学习如何使用称为“快速幂运算”的优化算法来计算a ^ b的值,即“ A”提高到幂“ B”

we could have used a brute force approach to do the required task but then it would have taken O(b) i.e a brute force approach can solve the required task in linear time whereas the same task could be done in O(log b) using FAST–EXPONENTIATION.

我们本可以使用蛮力方法来完成所需的任务,但随后它会采用O(b),即蛮力方法可以在线性时间内解决所需的任务,而相同的任务可以在O(log b)中使用快速赋权

Fast exponentiation uses a simple recursive approach whose recurrence relation can be written as :

快速求幂使用一种简单的递归方法,其递归关系可以写成:

F(a,b) = F(a,b/2)*F(a,b/2)

F(a,b)= F(a,b / 2)* F(a,b / 2)

From the above recurrence relation, it can be easily seen that the time complexity would be O(log b).

从上面的递归关系可以很容易地看出时间复杂度为O(log b)

C ++程序使用快速幂运算来查找A ^ B的值 (C++ program to find the value of A^B using fast exponentiation)

#include <iostream>
using namespace std;

//function to find a^b
int fcheck(int a,int b){
	if(b == 0)
	    return 1;
	if(b == 1)
		return a;
	return fcheck(a,b/2)*fcheck(a,b/2);
}

//main code
int main(){
	int a,b;

	cout<<"Enter the first number (value of a): ";
	cin>>a;
	cout<<"Enter the second number (Value of b): ";
	cin>>b;

	int x=fcheck(a,b);
	if(b%2==0 || b==1)
		cout<<a<<" raise to the power "<<b<<" is = " <<x<<endl;
	else
		cout<<a<<" raise to the power "<<b<<" is = " <<a*x<<endl;

	return 0;
}

Output

输出量

First run:
Enter the first number (value of a): 5
Enter the second number (Value of b): 3
5 raise to the power 3 is = 125

Second run:
Enter the first number (value of a): 5
Enter the second number (Value of b): 0
5 raise to the power 0 is = 1

Third run:
Enter the first number (value of a): 5
Enter the second number (Value of b): 1
5 raise to the power 1 is = 5


翻译自: https://www.includehelp.com/algorithms/compute-the-value-of-a-raise-to-the-power-b-using-fast-exponentiation.aspx

你可能感兴趣的:(c++,算法,java,python,数据结构)