快速幂和乘法

梦想游戏人
目录:
algorithm
unsigned long long   pow1(int x, int n)
{
	unsigned long long  r = 1;
	while (n--)r *= x;
	return r;
}


//二分快速幂 
unsigned long long   pow2(int x, int n)
{
	unsigned long long  r = 1, base = x;
	while (n)
	{
		if (n & 1)r *= base; // 如果是奇数
		base *= base;
		n >>= 1;
	}
	return r;


}

//二分快速乘法
unsigned long long   mult(int x, int n)
{
	unsigned long long  r = 0, base = x;
	while (n)
	{
		if (n & 1)r += base;
		cout <<n<<"        " << (n&1)<<"     "<< base<<"      "<<r << endl;
		base += base;
		n >>= 1;
	}
	return r;


}
Scroll Up