정수론(Number theory)

프로그래머스 Level1 > 정수 제곱근 판별

cepiloth 2018. 6. 14. 18:36
반응형

https://programmers.co.kr/learn/courses/30/lessons/12934


1. 문제 요약

임의의 정수 n에 대해, n이 어떤 정수 x의 제곱인지 아닌지 판단하려 합니다. n이 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.


2. 알고리즘

입력 받은 n 의 제곱근을 구한다. 

제곱근을 제곱하여 n 과 같다면 (n+1) * (n+1) 을 반환 한다.

다르다면 -1을 반환 한다.


3. 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string>
#include <vector>
#include <math.h>
#include <iostream>
 
using namespace std;
 
long long solution(long long n) {
    long long answer = 0;
    
    long long cand = sqrt(n);
    if(cand * cand == n) {
        answer = (cand+1)  * (cand+1);
    } else {
        answer = -1;
    }
    
    return answer;
}
cs

반응형