C-为了清晰起见,没有试图压缩代码
考虑输入:
A: A ∈ ℝ, A ≥ 1.0
B: B ∈ ℕ, B ≥ 1
这样,通常在should中应该只有一个解决方案,从而大大简化了问题。
代码是:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define TOLERANCE 1.0e-09
double tetrate(double, int);
int main(int argc, char **argv)
{
double target, max, min, mid, working;
int levels;
if (argc == 3)
{
target = atof(argv[1]); // A
levels = atoi(argv[2]); // B
// Shortcut if B == 1
if (levels == 1)
{
printf("%f\n", target);
return 0;
}
// Get a first approximation
max = 2.0;
while (tetrate(max, levels) < target)
max *= 2.0;
min = max / 2.0;
// printf("Answer is between %g and %g\n", min, max);
// Use bisection to get a closer approximation
do
{
mid = (min + max) / 2.0;
working = tetrate(mid, levels);
if (working > target)
max = mid;
else if (working < target)
min = mid;
else
break;
}
while (max - min > TOLERANCE);
// printf("%g: %f = %f tetrate %d\n", target, tetrate(mid, levels), mid, levels);
printf("%f\n", mid);
}
return 0;
}
double tetrate(double d, int i)
{
double result = d;
// If the result is already infinite, don't tetrate any more
while (--i && isfinite(result))
result = pow(d, result);
return result;
}
编译:
gcc -o tet_root tet_root.c -lm
跑步:
./tet_root A B
例如:
4 2
$ ./tet_root 65536 4
2.000000
3 3
$ ./tet_root 7625597484987 3
3.000000
3个 π
$ ./tet_root 1.340164183e18 3
3.141593
n(2½)➙2为n∞?(众所周知的限制)
$ ./tet_root 2 10
1.416190
$ ./tet_root 2 100
1.414214
$ ./tet_root 2 1000
1.414214
是!
n(e 1 / e)∞为n∞?(上限)
$ ./tet_root 9.999999999e199 100
1.445700
$ ./tet_root 9.999999999e199 1000
1.444678
$ ./tet_root 9.999999999e199 10000
1.444668
$ ./tet_root 9.999999999e199 100000
1.444668
凉!(e 1 / e≅1.44466786101 ...)