牛客网在线编程:优雅的点

题目:

链接:https://www.nowcoder.com/questionTerminal/0960cb46233b446687b77facc9148b89
来源:牛客网

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

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


输出描述:

输出为一个整数,即为优雅的点的个数
示例1
输入

25
输出

12

思路:

思路,在圆上的点则根据勾股定理,x^2+y^2=n.
但如果使用双循环的话,提交会超时。所以只用x从0-k循环,y取double值,判断与强制转化为int的y是否相同,如果相同则都为整数。
在输出时,如果x,y有一个是0,则count数+=2,否则+=4。
输出count即可

 1 import java.util.*;
 2 public class Youyadian {
 3     public static int Youya(int n){
 4         int x=0;
 5         int k=(int) Math.sqrt(n);
 6         int count = 0;
 7         //如果使用双循环,会超时
 8 //        for(x=0;x<=k;x++){
 9 //            for(y=0;y<=k;y++){
10 //                if(Math.pow(x, 2)+Math.pow(y, 2)==n){
11 //                    if(x==0||y==0){count+=2;}
12 //                    else{count+=4;}
13 ////                    System.out.print(x);
14 ////                    System.out.print(y);
15 ////                    System.out.println();
16 //
17 //                }
18 //            }
19 //        }
20         for(x = 0;x<=k;x++){
21              double y = Math.sqrt(n - x*x);
22              if((int)y==y){
23                  if(x==0||y==0){count+=2;}
24                     else{count+=4;} 
25              }
26         }
27         return count;
28     }
29     public static void main(String[] args) {
30         // TODO Auto-generated method stub
31         Scanner sc = new Scanner(System.in);
32         int count = 0;
33         while(sc.hasNext()){
34             int n = sc.nextInt();
35             System.out.println(Youyadian.Youya(n));
36         }
37     }
38 
39 }
原文地址:https://www.cnblogs.com/zlz099/p/8509860.html