码迷,mamicode.com
首页 > 其他好文 > 详细

求乘方的另一种思路

时间:2016-01-20 12:38:26      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

算法导论中提到,在求某个数乘方的时候,遵循的是减治法的思想。

这里是另外一种做法,通过对指数y进行二进制分解求乘方,比如x^y,当y=5时,求x^5=x^101,x*=x相当于求解x^10...0....0..,此算法时间复杂度是O(log(y)),代码如下:

#include <iostream>
int len(char *arr){
	int count=0;
	for (int i=0;arr[i]!=‘\0‘;i++)
	{
		count++;
	}
	return count;
}
void main(int argc,char* argv[]){
	int x=0,y=0;
	int result=1;
	printf("pls input two numbers:\n");
	scanf("%d",&x);
	scanf("%d",&y);
	char ch[256];
	itoa(y,ch,2);
	for(int i=len(ch)-1;i>=0;i--){
		if(ch[i]==‘1‘)
		{
			printf("%d\n",x);
			result*=x;
		}
		x*=x;
	}
      print("result:%d",result);
	system("pause");
}

  

求乘方的另一种思路

标签:

原文地址:http://www.cnblogs.com/wangjunyan/p/5144413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!