본문 바로가기
보관/자료구조-예제&실습

순환-거듭제곱 계산 알고리즘(2)

by unhyepnhj 2024. 9. 19.

https://sysouthelloworld.tistory.com/81

 

순환-거듭제곱 계산

순환을 사용하지 않고 x의 n제곱 값을 구하는 함수 작성double slow_power(double x, int n) { int i; double result = 1.0; for (i = 0; i - 루프 1회당 한 번의 곱셈이 필요하고 루프의 횟수는 n회- O(n)의 시간복잡도 

sysouthelloworld.tistory.com

위 글에 적지 않은 다른 방법이 더 있다.

double pow(int x, int n) {
	int res = 1;
	int a = x;

	while (n > 0) {
		if (n % 2 == 1) {	//excluded when remainder is 0
			res = res * a;
		}

		a *= a;
		n /= 2;	//quotient when n is divided by 2
	}

	return res;
}//O(logN)

 

e.g., x^29 = x^16 * x^8 * x^4 * x에 대해

a current value of n n % 2 res n/2
x 29 1 x 14
x^2 14 0 - 7
x*4 7 1 x * x^4 = x^5 3
x^8 3 1 x^5 * x^8 = x^13 1
x^16 1 1 x^13 * x&16 = x^29 0

 

십진수↔이진수 변환 알고리즘에서 차용?