快速幂(递归与非递归方式)

最平常的求幂方式:

public class problem50_3 {
	public double myPow(double x, int n) {
		//n可能为负
        long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        
        double res=1.0;
        
        for(int i=0;i<n;i++){
        	res=res*x;
        }

        return res;
    }
	public static void main(String[] args) {
		problem50_3 pro=new problem50_3();
		System.out.println(pro.myPow(2.10000, 3));
	}
}

快速幂:

public class problem50_2 {
	/*
	 * 迭代解快速幂
	 * n可能为负
	 */
	public double myPow(double x, int n) {
        long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        
        double res=1.0;
        double base=x;

        while(N!=0){
        	if(N%2!=0)
        		res*=base;
        	base*=base;
        	N=N/2;
        }

        return res;
    }
	public static void main(String[] args) {
		problem50_2 pro=new problem50_2();
		System.out.println(pro.myPow(2.10000, 3));
	}
}
public class problem50 {
	/*
	 * 递归解
	 * n可能为负
	 */
	public double myPow(double x, int n) {
        long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }

        return fastPow(x , N);
    }
	
	public double fastPow(double res,long n){
		if(n==0) return 1.0;
		
		double half=fastPow(res,n/2);
		
		if(n%2==0){
			return half*half;
		}else{
			return half*half*res;
		}
	}
	
	public static void main(String[] args) {
		problem50 pro=new problem50();
		System.out.println(pro.myPow(2.10000, 3));
	}
}

发布了31 篇原创文章 · 获赞 0 · 访问量 328

猜你喜欢

转载自blog.csdn.net/qq_36360463/article/details/104197190