Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ardrabczyk/7eb795d60df7ab6ec70d85e9ec3b04a5 to your computer and use it in GitHub Desktop.
Save ardrabczyk/7eb795d60df7ab6ec70d85e9ec3b04a5 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <float.h>
unsigned long long factorial(unsigned num)
{
unsigned int i = 1;
unsigned long long result = 1;
for (; i <= num; ++i)
{
if (result > ULLONG_MAX / i)
{
return 0;
}
result = result * i;
}
return result;
}
int factorial_rosetta(int n) {
int result = 1;
for (int i = 1; i <= n; ++i)
{
result *= i;
printf("result now: %d\n", result);
}
return result;
}
int main(void)
{
unsigned long long res = factorial(10);
if (res == 0)
{
puts("factorial(10) == Overflow");
}
else
{
printf("factorial(10) == %llu\n", res);
}
res = factorial(13);
if (res == 0)
{
puts("factorial(13) == Overflow");
}
else
{
printf("factorial(13) == %llu\n", res);
}
res = factorial(20);
if (res == 0)
{
puts("factorial(200) == Overflow");
}
else
{
printf("factorial(20) == %llu\n", res);
}
res = factorial(21);
if (res == 0)
{
puts("factorial(21) == Overflow");
}
else
{
printf("factorial(21) == %llu\n", res);
}
res = factorial(5000);
if (res == 0)
{
puts("factorial(5000) == Overflow");
}
else
{
printf("factorial(5000) == %llu\n", res);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment