How can calculate 37 decimals for Euler in C?
2128 is about 3.4*1038. By forming a 128 bit integer numerator/denominator we can achieve the desired e.
Re-writing the loop as below and running up to a large enough n
until num*i + 1
is about to overflow (n==33), we can arrive at/near the desired result.
// Algorithm
wide_floating_point e() {
unsigned n = 33;
my_uint128 num = 1;
my_uint128 den = 1;
for (unsigned i=1; i <= n; i++) {
num = num*i + 1;
den = den*i;
}
return (wide_floating_point) num/fact;
}
Now OP, may not have a 128 unsigned integer type, nor able to perform a 128/128 bit floating point divide. Yet OP only needs to create 2 functions (implementations not shown - but are essentially grade school math):
typedef struct {
// or unsigned char decimal_digit[40] or
// however you want to save a big integer
uint64_t hi,lo;
} my_uint128;
my_uint128 times_add_128(my_uint128 x, unsigned m, bool a);
void print_quotient_128(my_uint128 num, my_uint128 dem);
If we test the algoithm and use __int128
and use a long double
(with 80 precision) we get close to the goal.
long double e(int n) {
unsigned __int128 fact = 1;
unsigned __int128 num = 1;
for (int i=1; i<=n; i++) {
fact *= i;
if (num > (((unsigned __int128)-1)-1)/i) { printf("%d!\n", i); exit(0); }
num = num*i + 1;
}
return 1.0L*num/fact;
}
int main() {
for (int i=1; i<34; i++) {
printf("%d %.25Lf\n", i, e(i));
}
}
2,718281828459045235 3602874713526624977
33 2.718281828459045235 4281681
I leave the 2 functions times_add_128(), print_quotient_128()
for OP to code: