`
shenkun_918
  • 浏览: 26736 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

递归实现 :x的y次方

 
阅读更多

     计算机无法实现x的y次方,由

y =(x*x) (y/2)

来实现,依据此法,利用递归实现 x的y次方,在y为奇数的时候,提出一个x出来相乘,如下:

public class Power {
	
	static int xNum;
	public static void main(String[] args) throws IOException {
		
		int x,y;
		int count = 0;
		x = insert();
		y = insert();
		xNum = x;
		power(x,y,count);
	}

	private static void power(int x, int y, int count) {
		
		System.out.println("x值为:"+x+" y值为:"+y);
		if(y==1)
		{	
			if(count>0){
				for(int i=1;i<=count;i++){
					x = x*xNum;
				}
			}
			System.out.println("所求值为:"+x);
		}
		if(y>1)
		{ 
			
			//y为偶数的时候
			if(y%2==0)
			{	System.out.println(">>>>");
				power(x*x,y/2,count);
			}
			//y为奇数的时候
			if(y%2==1)
			{System.out.println("<<<<");
				power(x*x,(y-1)/2,count+1);
			}
		}
	}

	private static int insert() throws IOException {
		InputStreamReader in = new InputStreamReader(System.in);
		BufferedReader buffer = new BufferedReader(in);
		String s = buffer.readLine();
		return Integer.parseInt(s);
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics