2025华为OD机试题库(按算法分类):2025华为OD统一考试题库清单(持续收录中)以及考点说明(Python/JS/C/C++)。
专栏导读
本专栏收录于《华为OD机试真题(Python/JS/C/C++)》。
刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。
一、题目描述
等差数列 2,5,8,11,14。。。。
从 2 开始的 3 为公差的等差数列。
输出求等差数列前n项和。
数据范围: 1≤n≤1000 。
二、输入描述
输入一个正整数n。
三、输出描述
输出一个相加后的整数。
四、测试用例
1、输入
2
2、输出
7
五、解题思路
- 输入一个正整数n,表示要求等差数列前n项和;
- 计算等差数列的首项first,根据题目中的公差3和项数n可以得到:first = 2;
- 计算等差数列的末项last,根据题目中的公差3和项数n可以得到:last = 3 * n - 1;
- 使用等差数列求和公式计算前n项和,公式为:sum = (first + last) * n / 2;
- 输出sum作为结果。
六、Python算法源码
def arithmetic_sequence_sum(n):
# 首项
first = 2
# 末项
last = first + (n - 1) * 3
# 计算和
return (first + last) * n // 2
# 测试代码
test_cases = [1, 2, 3, 4, 5]
for n in test_cases:
print(arithmetic_sequence_sum(n))
七、JavaScript算法源码
function arithmeticSequenceSum(n) {
// 首项
const first = 2;
// 末项
const last = first + (n - 1) * 3;
// 计算和
return (first + last) * n / 2;
}
// 测试代码
const testCases = [1, 2, 3, 4, 5];
testCases.forEach(n => {
console.log(arithmeticSequenceSum(n));
});
八、C算法源码
#include <stdio.h>
int arithmetic_sequence_sum(int n) {
// 首项
int first = 2;
// 末项
int last = first + (n - 1) * 3;
// 计算和
return (first + last) * n / 2;
}
int main() {
int test_cases[] = {1, 2, 3, 4, 5};
int len = sizeof(test_cases) / sizeof(test_cases[0]);
for (int i = 0; i < len; i++) {
printf("%d\n", arithmetic_sequence_sum(test_cases[i]));
}
return 0;
}
九、C++算法源码
#include <iostream>
using namespace std;
int arithmetic_sequence_sum(int n) {
// 首项
int first = 2;
// 末项
int last = first + (n - 1) * 3;
// 计算和
return (first + last) * n / 2;
}
int main() {
int test_cases[] = {1, 2, 3, 4, 5};
int len = sizeof(test_cases) / sizeof(test_cases[0]);
for (int i = 0; i < len; i++) {
cout << arithmetic_sequence_sum(test_cases[i]) << endl;
}
return 0;
}
🏆下一篇:华为OD机试真题 - 简易内存池(Python/JS/C/C++ 2025 A卷 200分)
🏆本文收录于,华为OD机试真题(Python/JS/C/C++)
刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。