网易-优雅的点

https://www.nowcoder.com/practice/0960cb46233b446687b77facc9148b89?tpId=85&tqId=29851&tPage=1&rp=1&ru=/ta/2017test&qru=/ta/2017test/question-ranking

题目描述

小易有一个圆心在坐标原点的圆,小易知道圆的半径的平方。小易认为在圆上的点而且横纵坐标都是整数的点是优雅的,小易现在想寻找一个算法计算出优雅的点的个数,请你来帮帮他。
例如:半径的平方如果为25
优雅的点就有:(+/-3, +/-4), (+/-4, +/-3), (0, +/-5) (+/-5, 0),一共12个点。

输入描述:

输入为一个整数,即为圆半径的平方,范围在32位int范围内。

输出描述:

输出为一个整数,即为优雅的点的个数

示例1

输入

复制

25

输出

复制

12

题解:O(n^2)超时

#include <iostream>
#include <cmath>
using namespace std;
int main(){
  int n;
  while (cin >> n){
    int cnt = 0;
    float a = sqrt(n);
    if (a - (int)a == 0){
      cnt += 4;
    }
    for (int i = 1; i < sqrt(n); i++){
      int tmp = sqrt(n - i * i);
      if (tmp * tmp + i * i == n){
        cnt += 4;
      }
    }
    cout << cnt << endl;
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/reigns_/article/details/83017456