코테/프로그래머스

[프로그래머스/C++, C#] 두 원 사이의 정수 쌍

내꺼블로그 2024. 3. 4. 17:03

문제


https://school.programmers.co.kr/learn/courses/30/lessons/181187

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

코드


 

-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) : basen번 곱한 수.

sqrt(double or float or long double n) : n제곱근.

 

C#(using System)

Math.Sqrt(double n) : n의 제곱근

Math.Pow(double base, double n) : basen번 곱한 수

여기서도 MathF를 써버렸어서 오류가 났었다... double형을 할 때는 Math, float형을 할 때는 MathF 쓰기.

 

아무튼 x값이 0부터 r2이하일 때까지 for문을 돌려서 r2와 r1사이 존재할 수 있는 정수 y를 더했다.

사분면 중 하나만 구한 것이므로 answer값에 *4를 하고, x축 y축에 걸치는 좌표들은 중복되어 더해졌기 때문에 그 부분도 따로 빼면 구하려던 answer가 나온다.