Last active
October 18, 2022 18:41
-
-
Save shahril96/08ce05ca880b6e6d4e5d to your computer and use it in GitHub Desktop.
Factorial using __int128 integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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))); | |
} |
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)
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?
oops my bad
…On Sun, 9 Oct 2022, 04:15 Mohd Shahril, ***@***.***> wrote:
***@***.**** commented on this gist.
------------------------------
hi @alletsbckwrds <https://github.com/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?
—
Reply to this email directly, view it on GitHub
<https://gist.github.com/08ce05ca880b6e6d4e5d#gistcomment-4328822>, or
unsubscribe
<https://github.com/notifications/unsubscribe-auth/ALS23AKWHC73GJ6X57IAGG3WCITFPANCNFSM44KU5PPA>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice job 👍