프로그래밍/Ch
(최대공약수 구하기) while... 반복문 예제 for Ch
Scripter
2008. 2. 22. 11:52
소스 파일명: testWhileCPP.cpp
- /*
- * Filename: testWhileCPP.ch
- *
- * Purpose: Example using the while loop syntax
- * while ....
- *
- * Execute: ch testWhileCPP.ch -200 300
- */
- #include <iostream>
- #include <math.h>
- using namespace std;
- // 사용법 표시
- void printUsage() {
- cout << "Using: ch testWhileCPP.ch [integer1] [integer2]" << endl;
- cout << "This finds the greatest common divisor of the given two integers." << endl;
- }
- int main(int argc, char *argv[]) {
- long val1, val2;
- long a, b, q, r, gcd;
- if (argc != 3) {
- printUsage();
- exit(1);
- }
- // 명령행 인자의 두 스트링을 가져와서
- // 긴정수(long) 타입으로 변환하여
- // 변수 val1과 val2에 저장한다.
- val1 = atoi(argv[1]);
- val2 = atoi(argv[2]);
- // a는 |val1|, |val2| 중 큰 값
- a = abs(val1);
- b = abs(val2);
- if (a < b) {
- a = abs(val2);
- b = abs(val1);
- }
- if (b == 0L) {
- cout << "GCD(" << val1 << ", " << val2 << ") = " << a << endl;
- exit(0);
- }
- // -------------------------------------------
- // Euclidean 알고리즘의 시작
- //
- // a를 b로 나누어 몫은 q에, 나머지는 r에 저장
- q = a / b;
- r = a % b;
- // Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
- while (r != 0L) {
- a = b;
- b = r;
- q = a / b;
- r = a % b;
- }
- // 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
- gcd = b;
- // 최대공약수(GCD)를 출력한다.
- cout << "GCD(" << val1 << ", " << val2 << ") = " << gcd << endl;
- return 0;
- }
실행:
Command> ch testWhileCPP.ch
Using: ch testWhileCPP.ch [integer1] [integer2]
This finds the greatest common divisor of the given two integers.
Command> ch testWhileCPP.ch 200 -300
GCD(200, -300) = 100
Command> ch testWhileCPP.ch 0 -300
GCD(0, -300) = 300
Command> ch testWhileCPP.ch 20 -125
GCD(20, -125) = 5
Command> ch testWhileCPP.ch 121 66
GCD(121, 66) = 11
Command> ch testWhileCPP.ch -111 -37
GCD(-111, -37) = 37
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.