0
点赞
收藏
分享

微信扫一扫

蓝桥杯想拿奖?试试设计一个高效的求a的n次幂的算法


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

  • ​​思路​​
  • ​​题解​​

思路

首先呢,求a的n次幂实际上,java是有Math.pow()方法的,那如果我们自己手写来实现它,我们该如何写呢?

  • 思路1
    一个for循环,直接遍历,时间复杂度为O(n).
  • 思路2

每次a=a*a,直到大于a的n次幂,剩余的递归,时间复杂度为O(log2 n)

题解


public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub
int a=2,n=15;
System.out.println(pow0(a,n));
System.out.println(pow(a,n));
}

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

private static int pow(int a,int n) {
if(n==0) return 1;

int res=a;
int ex=1;
//能翻
while((ex<<1)<=n) {
//翻
res=res*res;
//指数
ex<<=1;//乘2
}
//不能翻
//差n-ex次方没有乘到结果里面
return res*pow(a,n-ex);
}
}


举报

相关推荐

0 条评论