objective-cintbigintegerfactorialnsuinteger

Returning Factorials greater than 12 in Objective-C


I have the following code, and I want it to give me factorial values up to 20.

-(NSUInteger)factorialofNumber(NSUInteger n){
static NSUInteger f[N + 1];
static NSUInteger i = 0;
if (i == 0)
{
    f[0] = 1;
    i = 1;
}
while (i <= n)
{
    f[i] = i * f[i - 1];
    i++;
}
return f[n];
}

The issue is that when this executes, all values above 12 are incorrect. I have placed this in my prefix file to try and have larger values available but it hasn't fixed the problem. Any hints to work around this?

#define NS_BUILD_32_LIKE_64 1

Solution

  • Factorial of 13 is bigger than 32 bit unsigned integer. Instead of NSUInteger you could use unsigned long long or uint64_t. This way you always get 64 bit values and keep binary compatibility, which might suffer with NS_BUILD_32_LIKE_64 declared. 64-Bit Transition Guide for Cocoa:

    The NS_BUILD_32_LIKE_64 macro is useful when binary compatibility is not a concern, such as when building an application.