From: vanjac12@... (Van Jacques) Date: 2003-12-15T03:02:01+09:00 Subject: Re: prog for g.c.d. of 2 integers "Robert Klemme" wrote in message news:... > "Van Jacques" schrieb im Newsbeitrag > news:70ae81fd.0312111642.26511e58@posting.google.com... > > I really wouldn't call it "mod" since that makes users expect to calculate > the equivalent of "a % b", which it doesn't. Yes, mod is not a good name. I was going to change it to gcd but never did. > > def mod(x,y) > > z = x % y > > if z == 0 > > return y > > else > > w = mod(y,z) > > end > > end > > > > puts "Enter the number of numbers for greatest common denominator." > > > > num = gets.chomp.to_i > > > > a = Array.new > > b = Array.new > > gcd = Array.new > > > > for i in 0...num > > a[i] = rand(999) + 1 > > end > > puts a > > You don't need to sort. Yes. I don't know what I was thinking of. > > b = a.sort.reverse > > puts b > > gcd[0] = mod(b[0],b[1]) > > > > for i in 2...num > > if (b[i] > gcd[i-2]) > > gcd[i-1] = mod(b[i],gcd[i-2]) > > else > > gcd[i-1] = mod(gcd[i-2],b[i]) > > end > > end > > puts gcd[num-2] > > =========== > > Kind of a more complicated version of inject. But why do you store the > results in an array? You just need one value: > > gcd = a.shift > a.each{|n|gcd=mod(gcd, n)} > puts gcd > > Kind regards > > robert Again, good point. I should "finish" my programs better. I developed some bad and sloppy habits since I wrote a lot of Fortran programs for research that I was the only one to read. I used a lot of arrays, and here I use them when they aren't required. The last 3 lines of your code > gcd = a.shift > a.each{|n|gcd=mod(gcd, n)} > puts gcd look like a good way to get the gcd of an arbitrary number of numbers. (with mod(x,y) --> gcd1(x,y), say). Van