Jimmy Kwon
Jimmy Kwon

Reputation: 21

Code for factorials in objective C

Using only for or while statements, I'm trying to come up with a program to generate and print a table of the first 10 factorials. Here's my code:

    for (count = 1; count<=10; ++count) 
    {
        n = count;
        while (n > 0){
            count *= (count-1);
            n -= 1;
        }
        NSLog(@"  %2g            %3g", count, factorial);
    }

I don't understand why this is not working. It never gets out of the loop and goes on forever. What's the correction? Thank you!

Upvotes: 2

Views: 4687

Answers (3)

Albert Renshaw
Albert Renshaw

Reputation: 17902

In Math, n! is the same thing as Γ(n+1) (see: http://en.wikipedia.org/wiki/Gamma_function)

So just use:

-(float)factorial:(float)number1 {
    return tgammaf(++number1);
}

This will even work for floats and negative numbers,

other solutions posted are long and extraneous and only work with positive integers.

Upvotes: 4

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21996

During the first loop iteration count is 1 and so also n is 1, then you enter the while and you set count to zero (count-1), and decrease n which becomes zero and you exit the while. So during the second loop iteration count will be zero. You keep decreasing count and it never gets increased, so you never exit the loop until a numeric overflow occurs.

You're doing it harder that what it is (and also inefficient) . Is enough that you keep multiplying n for count to get the factorial:

int n=1;
for (count = 1; count<=10; ++count) 
{
    n*= count;
    NSLog(@"%d",n);
}

Upvotes: 1

user529758
user529758

Reputation:

The reason:

count *= (count-1);

Since count starts at 1, it will always be reset to 0, so the count <= 10 condition of the outer loop will always be true, hence the infinite looping.

And you're overcomplicating it anyway.

for (int i = 1; i <= 10; i++) {
    int r = 1, n = i;
    while (n)
        r *= n--;

    printf("%d! = %d\n", i, r);
}

Upvotes: 4

Related Questions