思路
给大家分享一种 O ( n ) O(n) O(n) 的做法。我们把圆心看作坐标为 ( 0 , 0 ) (0,0) (0,0) 的点然后从圆心沿着横坐标不断扩展,在依次用勾股定理求出纵坐标上的正方形个数。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int r,ans;
main(){
cin>>r;
//沿着横坐标扩展。
for(int i=0;i<=r;i++){
int x,s;
x=(i+0.5)*(i+0.5);
//如果再扩展超过了圆就退出。
if(x>r*r) break;
//逆向勾股定理:已知斜边(r)和短边(i)求长边。
s=floor(sqrt(r*r-x)-0.5);
//我们要四个方向都算上
ans+=4*s;
}
//还有圆心的一个
cout<<ans+1;
}