Technically, you don't even need to use the factorial
or intmax
functions to solve this. Here's an example for an unsigned 64-bit integer type:
total = uint64(1); % Set the data type you want here
N = 1;
while (total == (total*(N+1))/(N+1))
N = N+1;
total = total*N;
end
disp(N)
And the output:
20 % Largest N for uint64 types that gives correct factorial(N)
This works due to the fact that data types have an upper limit on the size of the number they can represent. If you make the number too big, it will saturate at the maximum for integer types or lose precision for floating-point types (some interesting related information about precision here). The above loop keeps a running total
that stores the factorial up to N
and checks to see if multiplying then dividing by N+1
gives the same result, which it won't if the initial multiplication causes an overflow/precision loss.