COTE/programmers

[java] 정수 제곱근 판별

ihate404 2022. 5. 6. 18:42

 

 

자바의  java.lang.Math 클래스의 거듭제곱과 제곱근을 구하는 메소드를 사용하면 쉽게 풀이할 수 있다!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package www.gohome.com;
//정수 제곱근판별 
//임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
//n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요
public class DetermineTheSquareRootOfAnInteger {
        public static long solution(long n) {
            if(n == Math.pow((int)Math.sqrt(n), 2)) {
                return (long)(Math.pow(Math.sqrt(n)+12));
            }else {
                return -1;
            }
        
    }
    public static void main(String[]args) {
        DetermineTheSquareRootOfAnInteger d = new DetermineTheSquareRootOfAnInteger();
        System.out.println(d.solution(36));
    }
}
 
cs

 

거듭제곱 = Math.pow(대상 숫자, 제곱할 횟수) 

                ex)Math.pow(5,2); <--- 25.0 (입 출력값은 모두 double형)

제곱근(루트) = Math.sqrt(대상숫자)

                ex)Math.sqrt(25) <--- 5.0 (입 출력값은 모두 double형)

 

 


출처

https://coding-factory.tistory.com/531

 

[Java] 자바 거듭 제곱 구하기 Math.pow()

자바에서 특정값의 제곱을 구하려면 java.lang.Math 클래스의 pow()메소드를 사용하면 됩니다. java.lang.Math 클래스는 수학 계산에 사용할 수 있는 메소드를 제공하고 있습니다. Math 클래스가 제공하는

coding-factory.tistory.com

https://coding-factory.tistory.com/532

 

[Java] 자바 제곱근(루트) 구하기 Math.sqrt()

자바에서 특정값의 제곱근(루트)을 구하려면 java.lang.Math 클래스의 sqrt()메소드를 사용하면 됩니다. java.lang.Math 클래스는 수학 계산에 사용할 수 있는 메소드를 제공하고 있습니다. Math 클래스가

coding-factory.tistory.com