设计一个高效的求a的n次幂的算法

设计一个高效的求a的n次幂的算法

public class Main {
    public static void main(String[] args) {
        int res = pow(2,15);
        System.out.println(res);
    }

    public  static int pow0(int a,int n){
        int res = 1;
        for (int i=0;i<n;i++){
            res*=a;
        }
        return res;
    }

    public static int pow(int a , int n){
        if (n==0){
            return 1;
        }
        int ex = 1;
        int res =a;
        while((ex<<1)<=n){
            res *=res;
            ex <<=1;
        }

        return res*pow(a,n-ex);
    }
}
发布了40 篇原创文章 · 获赞 0 · 访问量 760

猜你喜欢

转载自blog.csdn.net/weixin_42463611/article/details/104479308