소스 파일명: testWhileCPP.cpp

  1. /*
  2.  * Filename: testWhileCPP.ch
  3.  *
  4.  * Purpose:  Example using the while loop syntax
  5.  *               while ....
  6.  *
  7.  * Execute:  ch testWhileCPP.ch -200 300
  8. */
  9. #include <iostream>
  10. #include <math.h>
  11. using namespace std;
  12. // 사용법 표시
  13. void printUsage() {
  14.     cout << "Using: ch testWhileCPP.ch [integer1] [integer2]" << endl;
  15.     cout << "This finds the greatest common divisor of the given two integers." << endl;
  16. }
  17. int main(int argc, char *argv[]) {
  18.     long val1, val2;
  19.     long a, b, q, r, gcd;
  20.     if (argc != 3) {
  21.         printUsage();
  22.         exit(1);
  23.     }
  24.     // 명령행 인자의 두 스트링을 가져와서
  25.     // 긴정수(long) 타입으로 변환하여
  26.     // 변수 val1과 val2에 저장한다.
  27.     val1 = atoi(argv[1]);
  28.     val2 = atoi(argv[2]);
  29.     // a는 |val1|, |val2| 중 큰 값
  30.     a = abs(val1);
  31.     b = abs(val2);
  32.     if (a < b) {
  33.         a = abs(val2);
  34.         b = abs(val1);
  35.     }
  36.     if (b == 0L) {
  37.         cout << "GCD(" << val1 << ", " << val2 << ") = " << a << endl;
  38.         exit(0);
  39.     }
  40.     // -------------------------------------------
  41.     // Euclidean 알고리즘의 시작
  42.     //
  43.     // a를 b로 나누어 몫은 q에, 나머지는 r에 저장
  44.     q = a / b;
  45.     r = a % b;
  46.     // Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
  47.     while (r != 0L) {
  48.         a = b;
  49.         b = r;
  50.         q = a / b;
  51.         r = a % b;
  52.     }
  53.     // 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
  54.     gcd = b;
  55.     // 최대공약수(GCD)를 출력한다.
  56.     cout << "GCD(" << val1 << ", " << val2 << ") = " << gcd << endl;
  57.     return 0;
  58. }



실행:

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





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,