乘方--java递归实现--循环实现

来源:互联网 发布:p.b是什么意思网络用语 编辑:程序博客网 时间:2024/05/22 00:36

1.主程序 

package recursion;//计算乘方public class Power {static long temp=1;        //--------递归实现乘方计算,时间O(logN)---------
public long calculate(long x, int y) {if (y == 1) {return x * temp;}if (y == 2) {return (x * x * temp);}if (y % 2 == 1) {temp = x;}return calculate(x * x, y / 2);}// ------------递归实现乘方,时间O(N)------------------------public long calculate2(long x, int y) {if (y == 1) {return x;} elsereturn x * calculate2(x, y - 1);}        //--------------循环实现乘方,时间O(N)------------------public long calculate3(long x, int y) {long result = 1;for (int i = 0; i < y; i++) {result = result * x;}return result;}}

2.测试程序

  

import recursion.Power;public class App {/** * @param args */public static void main(String[] args) {Power power = new Power();long result = power.calculate(5, 10);System.err.println(result);// ----------------------------result = power.calculate2(5, 10);System.err.println(result);// --------------------result = power.calculate3(5, 10);System.err.println(result);}}


3.测试结果

976562597656259765625


 

原创粉丝点击