Skip to content

Instantly share code, notes, and snippets.

@shahril96
Last active October 18, 2022 18:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahril96/08ce05ca880b6e6d4e5d to your computer and use it in GitHub Desktop.
Save shahril96/08ce05ca880b6e6d4e5d to your computer and use it in GitHub Desktop.
Factorial using __int128 integer
#include <stdio.h>
typedef unsigned __int128 uint128;
/* printing 128-bit value isn't official support yet
so here's implementation of converting 128-bit value into string */
char *str_uint128(uint128 n)
{
/* got confused about arithmetic operation with '0'? read more about ascii :) */
static char buf[1000] = {0}, *buft = buf;
int nbuf = 1000;
if (n == 0)
*buft = '0'; // obviously
else for(buft += nbuf - 2; n > 0; n /= 10) // ever heard else-for? ;)
*--buft = '0' + (n % 10);
return buft;
}
uint128 fact(int N) // calculate factorial with O(n)
{
uint128 n, i;
for(n = i = 1; i <= N; i++)
n *= i;
return n;
}
int main()
{
printf("%d! -> %s\n", 5, str_uint128(fact(5)));
printf("%d! -> %s\n", 10, str_uint128(fact(10)));
printf("%d! -> %s\n", 15, str_uint128(fact(15)));
}
@proXDhiya
Copy link

nice job 👍

@alletsbckwrds
Copy link

i tried implementing your function to get a string out of an unsigned __int128, but it only outputs 32 digits as the max value..? (i know there is no max value for this in limits.h, i calculated it myself subtracting 1 from 0)

@shahril96
Copy link
Author

hi @alletsbckwrds, i tried to reproduce but so far i got the expected value. see here: https://godbolt.org/z/xaM8h16vn
do you any example in code that i can use for testing?

@alletsbckwrds
Copy link

alletsbckwrds commented Oct 18, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment