首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

递归求积数

2012-08-28 
递归求乘方递归求一个数的乘方代码:仅仅是示例而已,实际应用中应该使用Java类库方法。?/** * calculate pow

递归求乘方

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

仅仅是示例而已,实际应用中应该使用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的表示范围,指数并不能无限大,仅作示例,没有修复这个缺陷!

?

热点排行