소스 파일명: TestWhileLoop.cs

  1. /*
  2.  *  Filename: TestWhileLoop.cs
  3.  *
  4.  *  Purpose:  Example using the while loop syntax
  5.  *                while ....
  6.  *
  7.  *  Compile: csc TestWhileLoop.cs
  8.  *  Execute: TestWhileLoop -200 300
  9.  *
  10.  */
  11. using System;
  12. namespace MyTestApplication1 {
  13.     public class TestWhileLoop {
  14.         // 사용법 표시
  15.         public static void PrintUsage() {
  16.             Console.WriteLine("Using: TestWhileLoop [integer1] [integer2]");
  17.             Console.WriteLine("This finds the greatest common divisor of the given two integers.");
  18.         }
  19.         // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
  20.         public static void Main(string[] args) {
  21.             if (args.Length != 2) {
  22.                 PrintUsage();
  23.                 Environment.Exit(1);
  24.             }
  25.             ////////////////////////////////////////////////
  26.             // 명령행 인자의 두 스트링을 가져와서
  27.             // 긴정수(long) 즉 Int64 타입으로 변환하여
  28.             // 변수 val1과 val2에 저장한다.
  29.             long val1 = Convert.ToInt64(args[0]);
  30.             long val2 = Convert.ToInt64(args[1]);
  31.             long a, b, q, r, gcd;    // r은 나머지, q는 몫
  32.             // a는 |val1|, |val2| 중 큰 값
  33.             a = Math.Abs(val1);
  34.             b = Math.Abs(val2);
  35.             if (a < b) {
  36.                 a = Math.Abs(val2);
  37.                 b = Math.Abs(val1);
  38.             }
  39.             if (b == 0L) {
  40.                 Console.WriteLine("GCD(" + val1 + ", " + val2 + ") = " + a);
  41.                 Environment.Exit(1);
  42.             }
  43.             ////////////////////////////////////////
  44.             // Euclidean 알고리즘의 시작
  45.             //
  46.             // a를 b로 나누어 몫은 q에, 나머지는 r에 저장
  47.             q = a / b;
  48.             r = a % b;
  49.             ////////////////////////////////////////
  50.             // Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
  51.                 while (r != 0L) {
  52.                 a = b;
  53.                 b = r;
  54.                 q = a / b;
  55.                 r = a % b;
  56.             }
  57.             // 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
  58.             gcd = b;
  59.             // 최대공약수(GCD)를 출력한다.
  60.             Console.WriteLine("GCD(" + val1 + ", " + val2 + ") = " + gcd);
  61.         }
  62.     }
  63. }


컴파일> csc -d . TestWhileLoop.cs

실행> TestWhileLoop
Using: TestWhileLoop [integer1] [integer2]
This finds the greatest common divisor of the given two integers.

실행> TestWhileLoop 200 300
GCD(200, 300) = 100

실행> TestWhileLoop 50 -20
GCD(50, -20) = 10

실행> TestWhileLoop -30 0
GCD(-30, 0) = 30




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

Posted by Scripter
,