728x90
반응형
1. 제곱, 제곱근, 지수
- 제곱
- 같은 수를 두 번 곱합
- 거듭 제곱: 같은 수를 거듭하여 곱함
- 2^3 = 2 x 2 x 2
- 제곱근 (=root, √ )
- a를 제곱하여 b가 될 때 a를 b의 제곱근이라고 함
- √ 4 = √ 2^2 = 2
2. 로그
- log a b
- a가 b가 되기 위해 제곱해야 하는 수
- log 2 4 = 2
3. 코드
// Math 함수 사용
// 제곱
Math.pow(2, 3); // 8
Math.pow(2, -3); // 1/8
// 제곱근
Math.sqrt(16); // 4
Math.pow(16, 1.0/2); // 4
// 절대 값
Math.abs(5); // 5
Math.abs(-5); // 5
// 로그
Math.E; // 2.718281828459045
Math.log(2.718281828459045) // 1
Math.log10(1000); // 3
// Math 함수 사용 X
// 제곱
private static double pow(int a, int b) {
double result = 1;
boolean isMinus = false;
if (b == 0) {
return 1;
} else if (b < 0) { // 음수인 경우
b *= -1
isMinus = true;
}
for (int i = 0; i < b; i++) {
result *= a;
}
return isMinus ? 1/result : result;
}
// 제곱근
private static double sqrt(int a) {
double result = 1;
for (int i = 0; i < 10; i++) {
result = (result + (a / result)) / 2;
}
return result;
}
728x90
반응형
'CS > 자료구조' 카테고리의 다른 글
[자료구조] 기초수학 문제 (0) | 2024.08.16 |
---|---|
[자료구조] 알고리즘 복잡도 (0) | 2024.08.15 |
[자료구조] 점화식과 재귀함수 (0) | 2024.08.15 |
[자료구조] 조합 (Combination) (0) | 2024.08.14 |
[자료구조] 순열 (Permutation) (0) | 2024.08.14 |