开发者

Java: Simple recursion function returns only 1

This is oddly my first Java application, I was wanting to implement an arbitrary precision factorial function, I did the recursive one fine but my iterative one simply outputs "1" and nothing else.. It is so late for me I can not spot why, I am not sure where I went wrong, is there something obvious here?

public static BigInteger ifact(BigInteger n) {
    BigInteger ret = new BigInteger("1");
    BigInteger i = new BigInteger("1");
    for(i = new BigInteger("0"); i.compareTo(n) == 0; i.add(new BigInteger("1"))){
        ret.multiply(i);
    }
    return ret;
}

In case you did not notice it uses the BigInteger package, hense the odd writings..

Also, like C, can you do something similar to typedef so I don't need to 开发者_高级运维type "BigInteger" each time?

EDIT: I think I meant to set ret as n, that may be it, or..maybe not.


In answer to your "typedef" question, no, you can't do that in Java.

As for your code, it has numerous mistakes. Your loop will only ever execute once, and only if n is equal to i. Why do you initialize i to 1 and then 0 at the beginning of the loop? Why do you ignore the result of i.add(...)? Why do you ignore the result of ret.multiply(i)? Remember, these methods don't change the BI itself!

This incorporates those changes:

    BigInteger n = BigInteger.valueOf(10);
    BigInteger ret = BigInteger.ONE;
    for (BigInteger i = BigInteger.ONE; i.compareTo(n) <= 0; i = i.add(BigInteger.ONE)) {
        ret = ret.multiply(i);
    }
    System.out.println(ret);


Try changing

ret.multiply(i);

to

ret = ret.multiply(i);


The BigInteger object is immutable (meaning you can't change it). In this way, it's like a String object. So, for this to work, you would want to change your line

ret.multiply(i);

to

ret = ret.multiply(i);


public static BigInteger ifact(BigInteger n) {
  BigInteger ret = BigInteger.ONE;
  for (BigInteger i = BigInteger.ONE; i.compareTo(n) <= 0; i = i.add(BigInteger.ONE)) {
    ret = ret.multiply(i);
  }
  return ret;
}
  1. ret = ret.multiply
  2. i.compareTo(n) <= 0
  3. BigInteger.ONE;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜