把嵌套根式看成递推 g_1=sqrt(1+x)、g_k=sqrt(k+g_{k-1}),从内向外一层循环折叠 n-1 次,O(n) 时间 O(1) 空间,保留两位小数输出。
OJ: roj
题目 ID: 1166
难度:入门
标签:递推数学python
创建: 2026-09-29 21:39
更新: 2026-10-05 04:06
题目描述
求 x n,输出 4.2 10,输出 3.68。
思路
令 g = sqrt(k + g)(printf("%.2f") 完成四舍五入与固定两位补零。
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 21:39
# update_at: 2026-09-29 21:39
import sys
from math import sqrt
def solve() -> None:
"""读入 x 与嵌套层数 n,按内层到外层展开 f(x,n) 并保留两位小数。"""
x, n = map(float, sys.stdin.buffer.read().split())
total = sqrt(1 + x) # 最内层 f(x,1) = sqrt(1+x),之后每层只看下一层的值
for k in range(2, int(n) + 1): # 外层 k 从 2 加到 n,把 sqrt(k + 下一层) 折叠进去
total = sqrt(k + total)
print(f"{total:.2f}")
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-05 04:06
* update_at: 2026-10-05 04:06
*/
// 求 f(x,n) = sqrt(n + sqrt(n-1 + ... + sqrt(2 + sqrt(1+x)))) 的值。
// 把嵌套根式看成递推 g_1 = sqrt(1+x)、g_k = sqrt(k + g_{k-1}),
// 从内层向外层一次循环折叠,O(n) 时间 O(1) 空间,保留两位小数输出。
#include <cstdio>
#include <cmath>
typedef long long ll;
double x; // 嵌套根式中的实数
ll n_layer; // 嵌套层数
int main() {
scanf("%lf %lld", &x, &n_layer);
double total = sqrt(1.0 + x); // 最内层 g_1 = sqrt(1+x)
// 从第 2 层折到第 n_layer 层,每层把层号 k 加进根号再开方
for (ll k = 2; k <= n_layer; k++) {
total = sqrt(k + total); // ll 与 double 相加自动提升为 double
}
printf("%.2f\n", total);
return 0;
}