Nuby: method defined in two classes


#1

Hi Friends,

I have the ff code below. It works but you can see that i have
duplicated the “is_odd?” method on both Fixnum and Bignum. I am just
asking for something more cleaner/elegant…

thanks and kind regards -botp

code follows…

:~/ruby # cat test1.rb
#-----------------------------------------------

http://acm.uva.es/p/v1/100.html

3n + 1 problem

#-----------------------------------------------

class Fixnum
def cycles_3n_1
n = self
my_loop do |i|
break i if n==1
if n.is_odd?
n = 3*n + 1
else
n = n / 2
end
end
end

def is_odd?
    self & 1 != 0
end

end

class Bignum
def is_odd?
self & 1 != 0
end
end

def my_loop
c = 1
loop do
yield c
c += 1
end
end

def get_max first, last
max = -1
first.upto(last) do |i|
c = i.cycles_3n_1
max = c if c>max
end
max
end

puts “from \t To \t Max Cycle \t Elapsed Time (sec)”
DATA.each do |pair|
time_start = Time.now
i,j = pair.split
k = get_max i.to_i, j.to_i
puts “#{i} \t #{j} \t #{k} \t\t #{Time.now-time_start}”
end

END
1 10
100 200
201 210
900 1000
1 1_000_000

:~/ruby # ruby test1.rb
from To Max Cycle Elapsed Time (sec)
1 10 20 0.001598
100 200 125 0.073956
201 210 89 0.005831
900 1000 174 0.094012
1 1_000_000 525 1801.349531


#2

Peña wrote:

Hi Friends,

I have the ff code below. It works but you can see that i have duplicated the “is_odd?” method on both Fixnum and Bignum. I am just asking for something more cleaner/elegant…

Why not define #is_odd? on Integer?


#3

Facets:

Integer#odd?

T.