문제
https://school.programmers.co.kr/learn/courses/30/lessons/181187
코드
-C++
#include <string>
#include <vector>
#include <cmath>
using namespace std;
long long solution(int r1, int r2) {
long long answer = 0;
for(int i=0;i<=r2;i++){
long long y1;
if(r1>=i)
y1 = (long long)ceil(sqrt(pow(r1, 2)-pow(i, 2)));
else
y1 = 0;
long long y2 = (long long)floor(sqrt(pow(r2, 2)-pow(i, 2)));
answer+=y2-y1+1;
}
answer*=4;
answer-=(r2-r1+1)*4;
return answer;
}
- C#
using System;
public class Solution {
public long solution(int r1, int r2) {
long answer = 0;
for(int i=0;i<=r2;i++){
long y1 = (long)Math.Ceiling(Math.Sqrt(Math.Pow(r1, 2)-Math.Pow(i, 2)));
if(r1<i)
y1 = 0;
long y2 = (long)Math.Truncate(Math.Sqrt(Math.Pow(r2, 2)-Math.Pow(i, 2)));
answer+=y2-y1+1;
}
answer-=r2-r1+1;
answer*=4;
return answer;
}
}
풀이
사실 다른 분 설명을 보았다... (자괴감 MAX)
수학을 내가 이렇게까지 못했었나 싶었던 순간..
x*x+y*y=r*r을 이용하여 y = sqrt(r*r-x*x)로 변형하여 x좌표별로 가능한(원점에서 (x,y)길이가 r1이상 r2이하인) y좌표 정수 개수를 더하면 되는 문제였다.
y가 double로 나올 수 있는데 이때는 큰 원보다는 작아야 되므로 r2를 대입했을 때는 내림, 작은 원보다는 커야 되므로 r1을 대입했을 때는 올림을 하면 되었다.
C++(#include<cmath>)
ceil(double or float or long double) : 올림
floor(double or float or long double) : 내림
C#(using System)
Math.Ceiling(double) : 올림
Math.Truncate(double) : 내림
이 부분 할때도 문제가 발생했었는데 Math로 하지 않고 MathF를 했더니 오류났었다..
Math의 매개변수는 double인 반면 MathF의 매개변수는 float이어서 발생한 문제였었던....쩝.
그래서 sqrt, pow 쓸 때도 문제가 되었었다.
C++(#include<cmath>)
pow(double or float or long double base, double or float or long double n) : base를 n번 곱한 수.
sqrt(double or float or long double n) : n의 제곱근.
C#(using System)
Math.Sqrt(double n) : n의 제곱근
Math.Pow(double base, double n) : base를 n번 곱한 수
여기서도 MathF를 써버렸어서 오류가 났었다... double형을 할 때는 Math, float형을 할 때는 MathF 쓰기.
아무튼 x값이 0부터 r2이하일 때까지 for문을 돌려서 r2와 r1사이 존재할 수 있는 정수 y를 더했다.
사분면 중 하나만 구한 것이므로 answer값에 *4를 하고, x축 y축에 걸치는 좌표들은 중복되어 더해졌기 때문에 그 부분도 따로 빼면 구하려던 answer가 나온다.
'코테 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/C#] 문자열 나누기 (0) | 2024.03.13 |
---|---|
[프로그래머스/C#] 서울에서 김서방 찾기 (0) | 2024.03.13 |
[프로그래머스/C++, C#] 달리기 경주 (0) | 2024.03.04 |
[프로그래머스/C++] 광물 캐기 (0) | 2024.02.28 |
[프로그래머스/C++] 산 모양 타일 (0) | 2024.02.26 |