-5

I am having problems writing a code in java to compute n! without recursion. I know how to do it in loops, but I am not sure how to do it non-recursively.

procedure factorial

if n = 1 or n = 0
return 1
if n>1
return(n*factorial(n-1))
end
Jongware
  • 22,200
  • 8
  • 54
  • 100
user135535
  • 11
  • 1
  • 3

1 Answers1

10

Here is an iterative solution:

int factorial(int n) {
    int f = 1;
    for(int i=1;i<=n;i++) {
        f *= i;
    }
    return f;
}
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
  • 2
    Good answer to a bad question, +1 – Aarowaim Apr 17 '14 at 22:20
  • Thanks! I'm not exactly sure what the question was asking, but I tried... – Anubian Noob Apr 17 '14 at 22:20
  • 1
    You should avoid using `int` as the return value, it will overflow very quickly use a `long`, or even better a `BigInteger` instead. – amit Apr 17 '14 at 22:29
  • @amit I disagree. Generally you want to return a primative, and int's are used a lot more than longs. You could write another method called "longFactorial" but... – Anubian Noob Apr 17 '14 at 22:30
  • No problem, it was an excellent start. As for using `BigInteger`, I echo that sentiment because it loses accurate results around 60! even when using `long` – Aarowaim Apr 17 '14 at 22:30
  • If you return a `long` java can convert it to `int` easily if you assign the return value to an `int`, using a simple cast. I'd still use a `BigInteger` anyway, but that's arguable. There is no real downside to using a `long` however. – amit Apr 17 '14 at 22:31