计算(148 - 10102) * D16 - 11012的结果,并选择答案的十进制值:( )
二、阅读程序(程序输入不超过数组或字符串定义的范围;判断题正确填√,错误填×;除特殊说明外,判断题1.5分,选择题3分,共计40分)
(1)
01 #include <iostream>
02 using namespace std;
03
04 bool isPrime(int n) {
05 if (n <= 1) {
06 return false;
07 }
08 for (int i = 2; i * i <= n; i++)
09 if (n % i == 0) {
10 return false;
11 }
12 }
13 return true;
14 }
15
16 int countPrimes(int n) {
17 int count = 0;
18 for (int i = 2; i <= n; i++)
19 if (isPrime(i)) {
20 count++;
21 }
22 }
23 return count;
24 }
25
26 int sumPrimes(int n) {
27 int sum = 0;
28 for (int i = 2; i <= n; i++) {
29 if (isPrime(i)) {
30 sum += i;
31 }
32 }
33 return sum;
34 }
35
36 int main( ) {
37 int x;
38 cin >> x;
39 cout << countPrimes(x) << " " << sumPrimes(x) << endl;
40 return 0;
41 }
(2)
01 #include <iostream>
02 #include <vector>
03 using namespace std;
04
05 int compute(vector<int> &cost) {
06 int n = cost.size( );
07 vector<int> dp(n + 1, 0);
08 dp[1] = cost[0];
09 for (int i = 2; i <= n; i++) {
10 dp[i] = min(dp[i-1], dp[i-2]) + cost[i-1];
11 }
12 return min(dp[n], dp[n-1]);
13 }
14
15 int main( ) {
16 int n;
17 cin >> n;
18 vector<int> cost(n);
19 for (int i = 0; i < n; i++) {
20 cin >> cost[i];
21 }
22 cout << compute(cost) << endl;
23 return 0;
24 }
(3)
01 #include <iostream>
02 #include <cmath>
03 using namespace std;
04
05 int customFunction(int a, int b) {
06 if (b == 0) {
07 return a;
08 }
09 return a + customFunction(a, b - 1);
10 }
11
12 int main( ) {
13 int x, y;
14 cin >> x >> y;
15 int result = customFunction(x, y);
16 cout << pow(result, 2) << endl;
17 return 0;
18 }
三、完善程序(单选题,每小题 3 分,共计 30 分)
(1) (判断平方数)
问题:给定一个正整数n,希望判断这个数是否为完全平方数,即存在一个正整数x使得x的平方为n。
试补全程序。
01 #include<iostream>
02 #include<vector>
03 using namespace std;
04 bool isSquare(int num) {
05 int i = __①__;
06 int bound = __②___;
07 for (; i <= bound; ++i) {
08 if (__③___) {
09 return __④___;
10 }
11 }
12 return __⑤___;
13 }
14 int main() {
15 int n;
16 cin >> n;
17 if (isSquare(n)) {
18 cout << n << " is a square number" << endl;
19 } else {
20 cout << n << " is not a square number" << endl;
21 }
22 return 0;
23 }
(2) (汉诺塔问题)
给定三根柱子,分别标记为A、B和C。初始状态下,柱子A上有若干个圆盘,这些圆盘从上到下按从小到大的顺序排列。任务是将这些圆盘全部移到柱子C上,且必须保持原有顺序不变。在移动过程中,需要遵守以下规则:
1. 只能从一根柱子的顶部取出圆盘,并将其放入另一根柱子的顶部。
2. 每次只能移动一个圆盘。
3. 小圆盘必须始终在大圆盘之上。
试补全程序
01 #include <iostream>
02 #include <vector>
03 using namespace std;
04
05 void move(char src, char tgt) {
06 cout << "从柱子" << src << "挪到柱子" << tgt << endl;
07 }
08 void dfs(int i, char src, char tmp, char tgt) {
09 if (i == __①___) {
10 move(__②___);
11 return;
12 }
13 dfs(i - 1, __③__);
14 move(src, tgt);
15 dfs(__⑤__, __④__);
16 }
17 int main() {
18 int n;
19 cin >> n;
20 dfs(n, 'A', 'B', 'C');
21 }