读书人

递归求积数

发布时间: 2012-08-28 12:37:01 作者: rapoo

递归求乘方

递归求一个数的乘方代码:

仅仅是示例而已,实际应用中应该使用Java类库方法。

?

/** * calculate power of a number recursively. * @author Sun Kui */public class Power {    private static int count = 1;    public static void main(String... args) {        if (args.length < 2) {            System.out.println("usage: java Power base exponent");            return;        }        int base = Integer.parseInt(args[0]);        int exponent = Integer.parseInt(args[1]);        Power p = new Power();        System.out.println(p.power(base, exponent));    }    public long power(long x, long y) {        if (y == 1) {            return x * count;        } else {            long tempX = x * x;            long tempY = y >> 1;            // if y is odd             if ((y & 0x01) == 1) {                count *= x;            }            return power(tempX, tempY);        }    }}

?限于long的表示范围,指数并不能无限大,仅作示例,没有修复这个缺陷!

?

读书人网 >编程

热点推荐