C — 명확성을 목표로 코드를 짜내려고하지 않았습니다.
입력 고려 :
A: A ∈ ℝ, A ≥ 1.0
B: B ∈ ℕ, B ≥ 1
그런 다음 ℝ에는 일반적으로 하나의 솔루션 만 있어야하므로 문제를 상당히 단순화합니다.
코드는 다음과 같습니다
#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 as n ➙ ∞? (잘 알려진 한계)
$ ./tet_root 2 10
1.416190
$ ./tet_root 2 100
1.414214
$ ./tet_root 2 1000
1.414214
예!
n (e 1 / e ) ➙ ∞ as 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 ...)