高效率的幂运算

 

例子:2^64==?

package heng.java.level2;

import java.util.Scanner;

public class powTest {
	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		while(input.hasNext()){
			int x = input.nextInt();
			int n = input.nextInt();
			long value = pow(x,n);
			System.out.println(value);
		}
	}
	public static boolean isEven(int m){
		boolean flag = false;
		if(m % 2 == 0){
			flag = true;
		}
		return flag;
	}
	public static long pow(long x, int n){
		if(n == 0){
			return 1;
		}
		if(n == 1){
			return x;
		}
		if(isEven(n)){//判断是不是偶数
			return pow(x*x, n/2);
		}else{
			return pow(x*x,n/2)*x;
		}
	}
}


 

 

posted @ 2013-09-12 22:21  pangbangb  阅读(205)  评论(0编辑  收藏  举报