views:

154

answers:

4

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.

+4  A: 

Try changing

ret.multiply(i);

to

ret = ret.multiply(i);
Scott
Just one mistake of many.
Mark Peters
+5  A: 

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);
Mark Peters
I keep thinking the statements = another statement, not just a function with a return value. I'll fix my stupid mistakes and update if I need any more help.. man I should not code at 6am..
John
I thank you alot for the example, that answers my question completely. I was up for the past 20 hours, a new language is hard to learn under this circumstance.. I kept fixing the code and not the logic.
John
+2  A: 

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);
Dante617
+1 for mentioning that BigIntegers are immutable
Andrei Fierbinteanu
A: 
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;
Thomas Langston