note
	description : "Command-line calculator for greatest common divisor of two integers"
	author		: "Karlheinz Hug"
	date		: "2007-11-07"
	revision	: "2010-11-29"

class GCD_CALCULATOR

create
	make

feature
	gcd_r (p, q : INTEGER) : INTEGER
				-- Greatest common divisor of p and q.
				-- Implemented by Euclid's algorithm, recursive.
		do
			debug
				print ("gcd_r (" + p.out + ", " + q.out + ") =%N") -- for testing only
			end
			if q = 0 then
				Result := p.abs
			else
				Result := gcd_r (q, p \\ q)
			end
		ensure
			final_result:			q = 0 implies Result = p.abs
			intermediate_result:	q /= 0 implies Result = gcd_r (q, p \\ q)
		end -- gcd_r

	gcd_i (p, q : INTEGER) : INTEGER
				-- Greatest common divisor of p and q.
				-- Implemented by Euclid's algorithm, iterative.
		local
			s, t : INTEGER
		do
			debug
				print ("gcd_i (" + p.out + ", " + q.out + ") =%N") -- for testing only
			end
			from
				Result := p.abs
				s := q.abs
			invariant
				0 <= Result and Result <= p.abs.max (q.abs)
				0 <= s and s <= q.abs
				gcd_i (Result, s) = gcd_i (p, q)
			until s <= 0 loop
				t := Result \\ s
				Result := s
				s := t
			variant
				s
			end
		ensure
			final_result:			q = 0 implies Result = p.abs
			intermediate_result:	q /= 0 implies Result = gcd_i (q, p \\ q)
		end -- gcd_i

feature {NONE}
	make (arguments : ARRAY [STRING])
			-- Given two integer command arguments, print their greatest common divisor.
		local
			p, q : INTEGER
		do
			if arguments = Void or else arguments.count < 3 or else
				not arguments.item (1).is_integer or else
				not arguments.item (2).is_integer
			then
				io.put_string ("Please call the gcd calculator with two integer arguments!")
			else
				p := arguments.item (1).to_integer
				q := arguments.item (2).to_integer
				io.put_string ("recursive: " + gcd_r (p, q).out); io.put_new_line
				io.put_string ("iterative: " + gcd_i (p, q).out)
			end
			io.put_new_line
		end -- make

end -- class GCD_CALCULATOR
