좌표평면을 좋아하는 진수는 x축과 y축이 직교하는 2차원 좌표평면에 점을 찍으면서 놀고 있습니다.
진수는 두 양의 정수 k, d가 주어질 때 다음과 같이 점을 찍으려 합니다.
a*k(a = 0, 1, 2, 3 ...)
, y축 방향으로 b*k(b = 0, 1, 2, 3 ...)
만큼 떨어진 위치에 점을 찍습니다.예를 들어,
k가 2, d가 4인 경우에는 (0, 0), (0, 2), (0, 4), (2, 0), (2, 2), (4, 0) 위치에
점을 찍어 총 6개의 점을 찍습니다.
정수 k와 원점과의 거리를 나타내는 정수 d가 주어졌을 때, 점이 총 몇 개 찍히는지 return 하는 solution 함수를 완성하세요.
- 1 ≤ k ≤ 1,000,000
- 1 ≤ d ≤ 1,000,000
import java.util.*;
class Node {
int x;
int y;
public Node(int x, int y){
this.x = x;
this.y = y;
}
}
class Solution {
public long solution(int k, int d) {
long answer = 0;
//2차원 좌표평면 -> (+,+)
//원점으로 부터 1~k까지, 1~k까지
//단, 원점과의 거리가 d를 넘는 위치에는 점을 찍지 않는다.
Node node = new Node(0,0);
while(node.x <= d){
//System.out.printf("(%d, %d)\n",node.x,node.y);
double x2 = Math.ceil(Math.pow(node.x,2));
double y2 = Math.ceil(Math.pow(node.y,2));
double dis = Math.sqrt(x2 + y2);
if(dis <= (double) d) {
answer += 1;
//System.out.printf("(%d, %d)\n",node.x,node.y);
}
node.y += k;
if(node.y > d) {
node.y = 0;
node.x += k;
}
}
return answer;
}
}
💥 8,11,13,14 시간 초과.
import java.util.*;
class Solution {
public long solution(int k, int d) {
long answer = 0;
//2차원 좌표평면 -> (+,+)
//원점으로 부터 1~k까지, 1~k까지
//단, 원점과의 거리가 d를 넘는 위치에는 점을 찍지 않는다.
for(int i = 0; i <= d; i+=k){
double x2 = Math.pow(i,2);
double d2 = Math.pow(d,2);
double dis = Math.sqrt(d2-x2);
answer += (long)(dis/(long)k)+1;
}
return answer;
}
}