解题思路
这是一个数列求和问题。需要计算数列前 项的和,其中每一项是前一项的平方根。
关键点:
- 每一项是前一项的平方根
- 需要保留2位小数
- 处理多组输入
- 使用 类型避免精度损失
算法步骤:
- 读取每组输入的 和
- 计算数列的每一项
- 累加求和
- 格式化输出结果
代码
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
double calculateSum(int n, int m) {
double sum = 0;
double current = n;
// 计算前m项的和
for (int i = 0; i < m; i++) {
sum += current;
current = sqrt(current);
}
return sum;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
Solution solution;
// 处理多组输入
while (cin >> n >> m) {
double result = solution.calculateSum(n, m);
// 设置输出格式
cout << fixed << setprecision(2) << result << endl;
}
return 0;
}
import java.util.*;
class Solution {
public double calculateSum(int n, int m) {
double sum = 0;
double current = n;
// 计算前m项的和
for (int i = 0; i < m; i++) {
sum += current;
current = Math.sqrt(current);
}
return sum;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Solution solution = new Solution();
// 处理多组输入
while (sc.hasNext()) {
int n = sc.nextInt();
int m = sc.nextInt();
double result = solution.calculateSum(n, m);
// 格式化输出
System.out.printf("%.2f%n", result);
}
sc.close();
}
}
import math
class Solution:
def calculate_sum(self, n: int, m: int) -> float:
sum_val = 0
current = n
# 计算前m项的和
for _ in range(m):
sum_val += current
current = math.sqrt(current)
return sum_val
def main():
solution = Solution()
# 处理多组输入
while True:
try:
n, m = map(int, input().split())
result = solution.calculate_sum(n, m)
# 格式化输出
print(f"{result:.2f}")
except EOFError:
break
if __name__ == "__main__":
main()
算法及复杂度
- 算法:直接模拟
- 时间复杂度:,其中 是数列项数
- 空间复杂度:,只需要常数空间