※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 9924번 문제인 The Euclidean Algorithm이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/9924 

 

9924번: The Euclidean Algorithm

The famous Euclidean algorithm is found in Book VII of the Elements. The Elements was written in 300 B.C.~by the Greek mathematician Euclid. It is rumored that King Ptolemy, having looked through the Elements, hopefully asked Euclid if there were not a sho

www.acmicpc.net

본문에 나와있는, 뺄셈을 이용한 유클리드 알고리즘을 그대로 구현하고, 해당 알고리즘이 몇 단계만에 종료되는지를 세어 문제를 해결할 수 있다.

 

단계가 진행될 때마다 A+B의 값은 항상 감소하므로 이와 같은 코드의 시간복잡도는 O(A+B)로 볼 수 있다. 이는 문제를 해결하기에 충분한 시간복잡도이다.

 

아래는 제출한 소스코드이다.

#include <iostream>
using namespace std;

int A, B, ans;

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	cin >> A >> B;
	while (A != B) {
		int AA = max(A, B) - min(A, B), BB = min(A, B);
		A = AA, B = BB;
		ans++;
	}

	cout << ans;
}
728x90

+ Recent posts