소스 파일명: testWhile.lsp
- #!/usr/bin/env clisp
- ;; Filename: testWhile.lsp
- ;;
- ;; Purpose: Example using the while loop syntax
- ;; (loop while (cond) do .... )
- ;;
- ;; Execute: clisp testWhile.lsp -200 300
- ;; 사용법 표시
- (defun printUsage()
- (format t "Usage: clisp testWhile.lsp [integer1] [integer2]~%")
- (format t "This finds the greatest common divisor of the given two integers.~%") )
- ;; 스트링을 부동소수점수로 변환하는 함수
- (defun parse-number (v)
- (with-input-from-string (s v) (read s)))
- (if (not(= (length ext:*args*) 2)) (printUsage))
- (if (not(= (length ext:*args*) 2)) (quit))
- ;; --------------------------------------
- ;; 명령행 인자의 두 스트링을 가져와서
- ;; 정수 타입으로 변환하여
- ;; 변수 val1과 val2에 저장한다.
- (setf val1 (parse-integer (nth 0 ext:*args*)))
- (setf val2 (parse-integer (nth 1 ext:*args*)))
- ;; a는 |val1|, |val2| 중 큰 값
- (setf a (abs val1))
- (setf b (abs val2))
- (setf once 1)
- (if (< a b) (loop while (= once 1) do
- (setf a (abs val2))
- (setf b (abs val1))
- (format t "a = ~D, b = ~D~%" a b)
- (setf once 0) ))
- ;; 블럭문이 두 개 이상의 문으로 구성되어 있으면 progn을 사용한다.
- (if (zerop b) (progn
- (format t "GCD(~D, ~D) = ~D~%" val1 val2 a)
- (quit) ))
- ;; --------------------------------------
- ;; Euclidean 알고리즘의 시작
- ;;
- ;; a를 b로 나누어 몫은 q에, 나머지는 r에 저장
- (setf q (floor (/ a b)))
- (setf r (mod a b))
- ; (format t "q = ~D, r = ~D~%" q r)
- ;; --------------------------------------
- ;; Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
- (loop while (not(zerop r)) do
- (setf a b)
- (setf b r)
- (setf q (floor (/ a b)))
- (setf r (mod a b)))
- ;; 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
- (setf gcd b)
- ;; 최대공약수(GCD)를 출력한다.
- (format t "GCD(~D, ~D) = ~D~%" val1 val2 gcd)
- (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
'프로그래밍 > Common Lisp' 카테고리의 다른 글
조립제법(Horner의 방법) 예제 for Common Lisp (0) | 2013.08.30 |
---|---|
80컬럼 컨솔에 19단표 출력하기 예제 for Common Lisp (0) | 2013.08.29 |
if...else... 조건문 사용 예제 for Common Lisp (0) | 2013.08.29 |
명령행 인자 처리 예제 for Common Lisp (0) | 2013.08.29 |
구구단 출력 예제 for Common Lisp (0) | 2013.08.29 |