소스 파일명: testWhile.lsp

  1. #!/usr/bin/env clisp
  2. ;; Filename: testWhile.lsp
  3. ;;
  4. ;;  Purpose:  Example using the while loop syntax
  5. ;;                (loop while (cond) do .... )
  6. ;;
  7. ;; Execute: clisp testWhile.lsp -200 300
  8. ;; 사용법 표시
  9. (defun printUsage()
  10.     (format t "Usage: clisp testWhile.lsp [integer1] [integer2]~%")
  11.     (format t "This finds the greatest common divisor of the given two integers.~%") )
  12. ;; 스트링을 부동소수점수로 변환하는 함수
  13. (defun parse-number (v)
  14.      (with-input-from-string (s v) (read s)))
  15. (if (not(= (length ext:*args*) 2)) (printUsage))
  16. (if (not(= (length ext:*args*) 2)) (quit))
  17. ;; --------------------------------------
  18. ;; 명령행 인자의 두 스트링을 가져와서
  19. ;; 정수 타입으로 변환하여
  20. ;; 변수 val1과 val2에 저장한다.
  21. (setf val1 (parse-integer (nth 0 ext:*args*)))
  22. (setf val2 (parse-integer (nth 1 ext:*args*)))
  23. ;; a는 |val1|, |val2| 중 큰 값
  24. (setf a (abs val1))
  25. (setf b (abs val2))
  26. (setf once 1)
  27. (if (< a b) (loop while (= once 1) do
  28.     (setf a (abs val2))
  29.     (setf b (abs val1))
  30.     (format t "a = ~D, b = ~D~%" a b)
  31.     (setf once 0) ))
  32. ;; 블럭문이 두 개 이상의 문으로 구성되어 있으면 progn을 사용한다.
  33. (if (zerop b) (progn
  34.     (format t "GCD(~D, ~D) = ~D~%" val1 val2 a)
  35.     (quit) ))
  36. ;; --------------------------------------
  37. ;; Euclidean 알고리즘의 시작
  38. ;;
  39. ;; a를 b로 나누어 몫은 q에, 나머지는 r에 저장
  40. (setf q (floor (/ a b)))
  41. (setf r (mod a b))
  42. ; (format t "q = ~D, r = ~D~%" q r)
  43. ;; --------------------------------------
  44. ;; Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
  45. (loop while (not(zerop r)) do
  46.     (setf a b)
  47.     (setf b r)
  48.     (setf q (floor (/ a b)))
  49.     (setf r (mod a b)))
  50. ;; 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
  51. (setf gcd b)
  52. ;; 최대공약수(GCD)를 출력한다.
  53. (format t "GCD(~D, ~D) = ~D~%" val1 val2 gcd)
  54. (quit)


실행:

Command> clisp testWhile.lsp
Usage: clisp testWhile.lsp [integer1] [integer2]
This finds the greatest common divisor of the given two integers.


Command> clisp testWhile.lsp -200 300
GCD(-200, 300) = 100

Command> clisp testWhile.lsp -200 0
GCD(-200, 0) = 200

Command> clisp testWhile.lsp 125 100
GCD(125, 100) = 25

Command> clisp testWhile.lsp 23 25
GCD(23, 25) = 1







Posted by Scripter
,