프로그래밍/Ruby
(최대공약수 구하기) while... 반복문 예제 for Ruby
Scripter
2008. 2. 21. 21:44
소스 파일명: testWhile.rb
- #
- # Filename: testWhile.rb
- #
- # Purpose: Example using the while loop syntax
- # while ....
- #
- # Execute: ruby testWhile.rb -200 300
- #
- # 사용법 표시
- def printUsage()
- print "Using: ruby testWhile.rb [integer1] [integer2]\n"
- print "This finds the greatest common divisor of the given two integers.\n"
- end
- if (ARGV.length != 2)
- printUsage()
- exit(1)
- end
- # --------------------------------------
- # 명령행 인자의 두 스트링을 가져와서
- # 정수 타입으로 변환하여
- # 변수 val1과 val2에 저장한다.
- val1 = ARGV[0].to_i
- val2 = ARGV[1].to_i
- # a는 |val1|, |val2| 중 큰 값
- a = val1.abs
- b = val2.abs
- if (a < b) then
- a = val2.abs
- b = val1.abs
- end
- if (b == 0)
- print "GCD(#{val1}, #{val2}) = #{a}\n"
- exit(0)
- end
- # --------------------------------------
- # Euclidean 알고리즘의 시작
- #
- # a를 b로 나누어 몫은 q에, 나머지는 r에 저장
- q = a / b
- r = a % b
- # --------------------------------------
- # Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
- while (r != 0)
- a = b
- b = r
- q = a / b
- r = a % b
- end
- # 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
- gcd = b
- # 최대공약수(GCD)를 출력한다
- print "GCD(#{val1}, #{val2}) = #{gcd}\n"
실행:
Command> ruby testWhile.rb
Using: ruby testWhile.rb [integer1] [integer2]
This finds the greatest common divisor of the given two integers.
Command> ruby testWhile.rb 23 25
GCD(23, 25) = 1
Command> ruby testWhile.rb 230 25
GCD(230, 25) = 5
Command> ruby testWhile.rb 230 125
GCD(230, 125) = 5
Command> ruby testWhile.rb -200 300
GCD(-200, 300) = 100
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.