# Range in a loop

Hello everyone, I have this code. You type in a number and then it
identifies whether it is odd or even. When it identifies an odd number,
it
will multiply it by three plus one. When It identifies an even number,
it will divide it by 2. This will carry on in a loop until it reaches
number 1, then the loop will stop.

After that, it will count all the numbers in the loop that were printed
in total. So, in other words, it displays the count of all printed
numbers in that loop.

Now I need to modify it into a range (of 2 numbers of course). So, for
instance you type in 10 and 50 (not only one number, but two) and it
will pick a number from that
range between 10 and 50 with the highest count(the longest odd and even
number loop) and display the highest count.

For example, it would display number 112… because that would be the
highest count of a number in that range of 10 and 50.

Thanks

Faith

The code is here:

def odd_even_numbers n # this function calculates next number in the
sequence
if n % 2 == 0 # identifies even number
return n / 2 # even number is divided by two
else
return n * 3+1 # odd number is multiplied by three plus one
end
end

counter = 1 # counts all displayed numbers

num = gets.to_i # changes into integer, reads it
while num > 1 # stops when it reaches number one
num = odd_even_numbers(num)
puts num
counter += 1
end

puts “In total, there were #{counter} numbers displayed” # displays the
count

yourself.

hello

this is simple; you could try yourself

anyway…

def odd_even_numbers n # this function calculates next number in the
sequence
if n % 2 == 0 # identifies even number
return n / 2 # even number is divided by two
else
return n * 3+1 # odd number is multiplied by three plus one
end
end

print “Give me two numbers (blank separated): "
num1, num2 = gets.chop.split(” ").map {|x| x.to_i } # changes into
max_seq = 0 ; max_seq_num = 0
num1.upto(num2) do |num|
n = num
counter = 1
while n > 1 # stops when it reaches number one
n = odd_even_numbers(n)
counter += 1
end
if counter > max_seq
max_seq = counter
max_seq_num = num
end
end

puts “Max seq lenght: #{max_seq}”
puts “Max seq num: #{max_seq_num}”

add controls, for instance to be sure that 2 numbers in input, num1 <
num2, and so on