Niuke—perfect square numbers (C++)

Perfect square number:

Perfect square numbers (nowcoder.com)

Question description

Query the number of perfect square numbers in the range [l,r] multiple times

Define an integer x to be a perfect square if and only if the integer y can be found such that y*y=x

Enter description:

A number n in the first line represents the number of queries, 
followed by two numbers l, r in each line of n lines.

Output description:

For each query, output a number representing the answer

Example 1

enter

Copy 5 1 3 1 4 2 4 4 4 1 1000000000

5
1 3
1 4
2 4
4 4
1 1000000000

output

Copy 1 2 1 1 31622

1
2
1
1
31622

Remark:

n <= 100000
0<= l <= r <= 1000000000

 Analysis: There are two ways to solve this problem. First, use the ordinary method, that is, use two int types sl and sr to store the square root values ​​of the two input numbers lefth and right, and consider whether sl*sl is equal to left. If they are equal, output sr-sl+1, otherwise output sr-sl. The specific code is as follows:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int T;
    cin>>T;
    while(T--){
        int left,right;
        cin>> left >> right;
        int sl=sqrt(left),sr=sqrt(right);
        if(sl*sl==left){
            cout << sr-sl+1 << endl;
        }
        else{
            cout << sr-sl << endl;
        }
    }
}

Method Two:

This method is mainly used to examine the binary search method in an ordered array, using the functions lower_power() and upper_lower().

Use the lower_bound() and upper_bound() functions in the binary search method to solve the problem. From the data range of the question, the square root of the maximum data does not exceed 31625. Then create an array to store all the data from 1 to 31625. The square root you are looking for is certain. In this array, subtract the subscript of the square root of the first number greater than or equal to the left border from the subscript of the square root of the first number greater than the right border in the array to get the final answer. The specific code is as follows:

#include<bits/stdc++.h>
using namespace std;
const int N=31625;
int a[N];
int main()
{
    int T;
    cin >> T;
    for(int i=1;i<N;i++){
        a[i]=i;
    }//创建数组
    while(T--){
        int left,right;
        cin >> left >> right;
        int l=lower_bound(a,a+N,sqrt(left))-a;//第一个大于等于左边界平方根的数字的下标
        int r=upper_bound(a,a+N,sqrt(right))-a;//第一个大于右边界平方根的数字的下标
        cout << r-l << endl;
    }
}

Guess you like

Origin blog.csdn.net/m0_74472474/article/details/132788376