제곱, 제곱근, 지수

제곱

- 같은 수를 두 번 곱함

- 거듭 제곱: 같은 수를 거듭하여 곱함

 

제곱근 (=root)

- a를 제곱하여 b가 될 때 a를 b의 제곱근이라고 함

로그

- a가 b가 되기 위해 제곱해야 하는 수

ex) log10이 1000이 되기 위해 제곱해야 되는 수는 3제곱


실습 코드

// 기초 수학 - 지수와 로그

public class Main {

    public static void main(String[] args) {

//      1. 제곱, 제곱근, 지수
        System.out.println("== 제곱 ==");
        System.out.println(Math.pow(2, 3));
        System.out.println(Math.pow(2, -3));
        System.out.println(Math.pow(-2, -3));

        System.out.println(Math.pow(2, 30));
        System.out.printf("%.0f\n", Math.pow(2, 30));

        System.out.println("== 제곱근 ==");
        System.out.println(Math.sqrt(16));
        System.out.println(Math.pow(16, 1.0/2));
        System.out.println(Math.pow(16, 1.0/4));

//      참고) 절대 값
        System.out.println("== 절대 값 ==");
        System.out.println(Math.abs(5));
        System.out.println(Math.abs(-5));

//      2. 로그
        System.out.println("== 로그 ==");
        System.out.println(Math.E);
        System.out.println(Math.log(2.718281828459045));
        System.out.println(Math.log10(1000));
        System.out.println(Math.log(4) / Math.log(2));
    }
}


연습 코드

// Practice
// 제곱과 제곱근을 Math 없이 구현하기

public class Practice {

    // 기본적인 제곱 형태
    // 반환은 double 타입으로 밑은 int 지수 승은 double 형태로 받도록 만듬
    static double pow(int a, double b) {
        double result = 1; // 반환을 위한 변수 만들기
        boolean isMinus = false; // 음수 여부 판단을 위한 변수 만들기

        if (b == 0) { // 어떤 수의 0제곱은 1이니깐
            return 1;
        } else if (b < 0) {
            b *= -1;
            isMinus = true; // 음수가 들어왔다는 의미로 true로 만들어줌
        }

        for (int i = 0; i < b; i++) {
            result *= a;
        }
        return isMinus ? 1 / result : result; // 음수면 나눠서 리턴해주고 아니면 그대로 리턴을 해라
    }

    // 제곱근 구하기
    static double sqrt(int a) {
        double result = 1;

        for (int i = 0; i < 10; i++) { // 많이 하면 할수록 근삿값에 가까워진다. 우선 10번으로 지정
            result = (result + (a / result)) / 2;
        }
        return result;
    }


    public static void main(String[] args) {

//      Test code
        System.out.println("== Math pow ==");
        System.out.println(Math.pow(2, 3));
        System.out.println(Math.pow(2, -3));
        System.out.println(Math.pow(-2, -3));

        System.out.println("== My pow ==");
        System.out.println(pow(2, 3));
        System.out.println(pow(2, -3));
        System.out.println(pow(-2, -3));

        System.out.println("== Math sqrt ==");
        System.out.println(Math.sqrt(16));
        System.out.println(Math.sqrt(8));

        System.out.println("== My sqrt ==");
        System.out.println(sqrt(16));
        System.out.println(sqrt(8));

    }
}

'자료구조 l 알고리즘 > Ch. 01. 기초 수학' 카테고리의 다른 글

알고리즘 복잡도  (0) 2023.03.16
점화식과 재귀함수  (0) 2023.03.16
조합  (0) 2023.03.15
순열  (0) 2023.03.14
경우의 수  (0) 2023.03.14