제곱근(square root)을 구하는 메서드예요.
Math.sqrt(숫자) // 제곱근 반환
double을 반환해요double result = Math.sqrt(16); // 4.0
Math.sqrt(4); // 2.0
Math.sqrt(9); // 3.0
Math.sqrt(16); // 4.0
Math.sqrt(25); // 5.0
Math.sqrt(121); // 11.0
어떤 수가 완전제곱수인지 확인할 때 유용해요.
public boolean isPerfectSquare(int n) {
int sqrt = (int) Math.sqrt(n);
return sqrt * sqrt == n;
}
isPerfectSquare(16); // true (4*4=16)
isPerfectSquare(15); // false
double sqrt = Math.sqrt(121); // 11.0 (double)
int x = (int) Math.sqrt(121); // 11 (int로 변환)
long y = (long) Math.sqrt(121); // 11 (long으로 변환)
class Solution {
public long solution(long n) {
long x = (long) Math.sqrt(n);
if(x * x == n) {
return (x + 1) * (x + 1);
}
return -1;
}
}
solution(121); // 144 (11의 제곱 → 12의 제곱)
solution(3); // -1 (제곱수 아님)
public int countDivisors(int n) {
int count = 0;
for(int i = 1; i <= Math.sqrt(n); i++) {
if(n % i == 0) {
count += (i * i == n) ? 1 : 2;
}
}
return count;
}
countDivisors(36); // 9개 (1,2,3,4,6,9,12,18,36)
Math.sqrt(-1); // NaN (Not a Number)
Math.sqrt(-16); // NaN
Math.sqrt(0); // 0.0
Math.sqrt(1); // 1.0
Math.sqrt(2); // 1.4142135623730951
Math.sqrt(3); // 1.7320508075688772
Math.sqrt(0.25); // 0.5 (√0.25 = 0.5)
// n까지 모두 반복 (매우 느림!)
for(int i = 1; i <= n; i++) {
if(i * i == n) return i;
}
// 제곱근까지만 반복
for(int i = 1; i <= Math.sqrt(n); i++) {
if(i * i == n) return i;
}
// 바로 제곱근 계산
int x = (int) Math.sqrt(n);
if(x * x == n) return x;
// 제곱
Math.pow(2, 3); // 8.0 (2의 3제곱)
// 제곱근
Math.sqrt(16); // 4.0
// 절댓값
Math.abs(-5); // 5
// 최댓값/최솟값
Math.max(10, 20); // 20
Math.min(10, 20); // 10
// 올림/내림/반올림
Math.ceil(3.2); // 4.0 (올림)
Math.floor(3.8); // 3.0 (내림)
Math.round(3.5); // 4 (반올림)
int n = 121;
int x = Math.sqrt(n); // ❌ 컴파일 에러! (double을 int에 못 담음)
int x = (int) Math.sqrt(n); // ✅ 형변환 필요
long n = 121;
long x = (long) Math.sqrt(n);
// ✅ 올바른 확인
if(x * x == n) { ... }
// ❌ 틀린 확인
if(Math.sqrt(n) == x) { ... } // 부동소수점 오차 가능
public int sqrt(int n) {
return (int) Math.sqrt(n); // ❌ 음수면 NaN 반환
}
// ✅ 음수 체크
public int sqrt(int n) {
if(n < 0) return -1;
return (int) Math.sqrt(n);
}
| 항목 | 설명 |
|---|---|
| 메서드 | Math.sqrt(double a) |
| 반환 타입 | double |
| 용도 | 제곱근 계산 |
| 형변환 | (int) 또는 (long) 필요 |
| 음수 | NaN 반환 |
// 입력: 16 → 출력: true
// 입력: 15 → 출력: false
public boolean isPerfectSquare(int n) {
// 코드 작성
}
// 입력: 121 → 출력: 144
// 입력: 3 → 출력: -1
public long solution(long n) {
// 코드 작성
}
// 문제 1
public boolean isPerfectSquare(int n) {
int sqrt = (int) Math.sqrt(n);
return sqrt * sqrt == n;
}
// 문제 2
public long solution(long n) {
long x = (long) Math.sqrt(n);
return x * x == n ? (x + 1) * (x + 1) : -1;
}
Math.pow(a, b) - 거듭제곱Math.abs(a) - 절댓값Math.max(a, b) - 최댓값Math.min(a, b) - 최솟값핵심: 제곱근이 필요하면 반복문 대신 Math.sqrt()를 사용