Algorithm/C++ - 프로그래머스

프로그래머스 - 정수 제곱근 판별 C++

ㅇㅇ잉 2021. 2. 23. 21:12

sqrt는 double, float, long double형이 올 수 있고

매개변수로 들어온 숫자의 제곱근을 반환해주는 함수이다.

<cmath>라이브러리에 있다.

 

양의 정수인 제곱근을 찾아야 하므로, (int)를 붙여주어 제곱근과 붙이지 않고 구한 제곱근이 서로 같다면 answer를 계산하여 넣어주면 끝.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <string>
#include <vector>
#include <cmath>
using namespace std;
 
long long solution(long long n) {
    long long answer = -1;
    
    if(sqrt(n)==(int)sqrt(n)){
        answer=(sqrt(n)+1)*(sqrt(n)+1);
    }
    return answer;
}
cs

 

아래는 다른 분이 푸신 코드인데,

pow를 이용해서 푼 코드이다.

 

pow는 <cmath>라이브러리로

answer에 미리 sqrt(n)를 넣고,

answer를 제곱했을 때 n과 같으면 제곱근+1의 제곱을 return시켜주고, 그렇지 않으면 -1을 return시켜주는 코드이다.

1
2
3
4
5
6
7
8
9
10
#include <string>
#include <vector>
#include <math.h>
using namespace std;
 
long long solution(long long n) {
    long long answer = sqrt(n);
 
    return powl(answer, 2== n ? powl(answer + 12) : -1;
}
cs