Read sections 3.1-3.3 in chapter 3 of the textbook Explorations in Computing.
Consider the following iterative function that computes the LCM of integers x and y, for x > 0 and y > 0:
def lcm(x,y)
p = x * y
while y != 0 do
temp = y
y = x % y
x = temp
q = p / x
end
return q
end
Show how this function computes lcm(21,49) by creating a table that shows the values of each variable at the end of each iteration of the loop. We have started the table for you with the initial values of the variables before the first iteration of the loop:
===================================== x y temp p q ===================================== 21 49 --- 1029 --- =====================================
1. Set total equal to 0. 2. Set i equal to 1. 3. While i is less than or equal to n, do the following: a. Add i to total. b. Add 1 to i. 4. Return total / n.
def compute_average(n) end
def compute_average2(n) end
def findmax(list)
max = list[0]
for i in 1..(list.length-1) do
if list[i] > max then
max = list[i]
end
end
return max
end
===================================== list max i ===================================== [5,7,3,2] 5 --- =====================================
def table(n)
for i in 1..n do
for j in 1..n do
print i*j, "\t"
end
puts
end
return nil
end
def sum(list)
total = 0
for i in list do
total = total + i
end
print total
end
Suppose that you are given two lists, list1 and list2 and you wish to compute the sum of all the integers in the two lists by the following Ruby expression.
sum_two_lists = sum(list1) + sum(list2)
What would need to be changed in the definition of sum(list) for the above assignment to be performed without any errors?