Development Palette

분할 정복 기법 본문

Algorithm/개념

분할 정복 기법

징주 2021. 8. 18. 00:30

반으로 나누어 각각 해결하고 또 나누어 해결하는 식을 반복하여 마지막에 통합하여 해답을 찾는다.

package com.ssafy.w0817;

import java.util.Scanner;

//분할 정복 알고리즘과 재귀 비교
//호출횟수만 비교하기 위해 코딩한 것(값의 오버플로우 생각하지 않고)
//분할정복이 월등히 적은 횟수
public class SquareNumber_분할정복 {
	
	//재귀
	static int callCnt;
	static long exp1(long x,long y) {
		callCnt++;
		if(y==1) return x;
		
		return x *exp1(x, y-1);
	}
	
	// 분할정복
	static long exp2(long x,long y) {
		callCnt++;
		
		if(y==1) return x;
		
		long r = exp2(x,y/2);
		long res = r*r;
		
		if(y%2==1) res *= x; // 홀수일때
		
		return res;
	}
	
	
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		int y = sc.nextInt();
		
//		System.out.println(exp1(x,y));
		System.out.println(exp2(x,y));
		System.out.println(callCnt);
		
	}

}

'Algorithm > 개념' 카테고리의 다른 글

[순열, 조합] NextPermutation  (0) 2021.08.18
이진 검색  (0) 2021.08.18
그리디, 탐욕 알고리즘  (0) 2021.08.18
2차원 배열 지그재그  (0) 2021.08.05
[재귀, 브루트포스] 순열, 조합, 부분집합  (0) 2021.08.04
Comments