原题链接:
J-平方根_河南萌新联赛2024第(五)场:信息工程大学 (nowcoder.com)
题目描述:
输入描述:
输出描述:
输入
2
27
16
输出
5
4
方法一:
利用数据类型转化自动向下取整的特性
#include<bits/stdc++.h>
using namespace std;
void solve()
{
long long n;
cin>>n;
cout<<(long long)sqrt(n)<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin>>t;
while(t--)
{
solve();
}
return 0;
}
方法二:
二分
#include<bits/stdc++.h>
using namespace std;
void solve()
{
long long n;
cin>>n;
int l=1;
int r=2e9;
while(l<r)
{
int mid=l+(r-l+1)/2;
if(1LL*mid*mid<=n) l=mid;
else r=mid-1;
}
cout<<l<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin>>t;
while(t--)
{
solve();
}
return 0;
}