본문 바로가기

Architecture for Software/Algorithm

최대 공약수 구하기

최대 공약수(GCD, Greatest Common Divisor)를 구하는 알고리즘을 올립니다.
휴~ 모두 간만에 하나 헷갈리는군요~ Java로 최대 공약수 구하는 알고리즘을 찾는 분에게 도움이 되었으면 좋겠습니다.
/**
 * Copyright (C) 2009, http://www.softwareinlife.com
 *
 * This file is part of "Software in Life".
 *
 * "Vision Software in Life" is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 */
package com.softwareinlife.codes;

/**
 * GCD
 * 
 * @author Jang, Sun-Jin (jangsunjin@softwareinlife.com)
 * @date 2009. 11. 9.
 * 
 */
public class GCD {

	public static int count = 0;

	/**
	 * Constructor
	 */
	public GCD() {
		super();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		GCD gcd = new GCD();
		int res = gcd.solve(15135, 9823);
//		int res = gcd.solve(3000, 2025);
//		int res = gcd.solve(280, 30);
		
		System.out.print("The Greatest Common Divisor: " + res);
		System.out.print("\t");
		System.out.print("(Count: " + count + ")");
	}

	/**
	 * Solve
	 * 
	 * @param j
	 * @param i
	 */
	private int solve(int u, int v) {
		int r = 0;
		int c = 0;

		if (u > v) {
			r = u % v;
			c = v;
		} else {
			r = v % u;
			c = u;
		}

		count ++;
		
		if (r == 0) {
			return c;
		} else {
			return solve(r, c);
		}
	}
}

'Architecture for Software > Algorithm' 카테고리의 다른 글

RLE(Run-Length Encoding) 알고리즘  (2) 2009.11.09
Top Coder에 도전하세요!  (4) 2009.01.01
Algorithm 이란  (0) 2008.11.17
The 3n+1 Problem  (3) 2008.11.11
스택(Stack)  (0) 2008.10.08