Learn C++ from a baby! Record the questions in the process of CSP-J preparation and study, and record every moment.
Attached is a summary post: Analysis of the real questions of the CSP-J preliminary competition over the years | Summary
#include <iostream>
using namespace std;
int n, k;
int solve1() //返回使得x²≤n的最大整数x
{
int l = 0, r = n;
while (l<=r) {
int mid = (l+r)/2;
if (mid * mid <= n) l = mid+1;
else r = mid -1;
}
return l -1; //l-1是满足(l-1)²≤n的最大数
}
double solve2(double x)
{
if (x == 0) return x;
for (int i=0; i<k; i++)
x = (x + n/x) / 2; //假设x数列有极限A,随着k增加,xi会越来越接近√n
return x;
}
int main()
{
cin >> n >> k;
double ans = solve2(solve1());
cout << ans << ' ' << (ans * ans == n) << endl;
return 0;
}
Assuming that int is a 32-bit signed integer type, the input n is a natural number not exceeding 47000, and k is a natural number not exceeding the range represented by int, complete the following judgment questions and multiple choice questions:
28. The most accurate time complexity analysis result of this algorithm is O(logn+k). ( )
[Answer]: yes
【Analysis】
The time complexity of solve1 is logn, and the time complexity of solve2 is k
29. When the input is "9801 1", the first number output is "99". ( )
[Answer]: yes
【Analysis】
The function of sovle1 is to find the square root of n. When n=9801, the square root of n is 99
30. For any input n, as the input k increases, the second output number will become "1". ( )
[Answer]: wrong
【Analysis】
If n is not the square of an integer, ans will be close to √n but not equal to √n due to round-off errors. The reason is that the double type will have a truncation error during the operation. For example, input "3 10", loop to the back, x is unchanged
31. The program has flaws. When the input n is too large, the multiplication in line 12 may overflow, so mid should be converted to a 64-bit integer before calculation. ( )
[Answer]: wrong
【Analysis】
The maximum value is (47000/2)^2, which does not exceed the maximum value of int 2147483647
32. When the input is "2 1", the first number output is closest to ( ).
A.1
B.1.414
C.1.5
D.2
[Answer]: C
【Analysis】
Substituting into the calculation, we get 1.5
33. When the input is "3 10", the first number output is closest to ( ).
A.1.7
B.1.732
C.1.75
D.2
[Answer]: B
【Analysis】
Substitute into the calculation to get √3. After several cycles of solve2, you will find that the value of x no longer changes
34. When the input is "256 11", the first number to output ( ).
A. is equal to 16
B. Close to but less than 16
C. Close to but greater than 16
D. The first three situations are all possible
[Answer]: A
【Analysis】
Same as question 29, the result is equal to 16