Calculation of Factorial in Ruby

0

Create a Ruby script that reads 10 integers and stores them in an array. Then, the script must calculate the factorial of each of these 10 numbers, and store the results in another array, and print the values.

I can not hit the factorial and storage calculation on the other array (array2). I ask for your help!

My code:

array1 = []

for i in 0..10
  puts "Digite um numero:"
  array1.push(gets.to_i)
end

def fatorial (n)
    if(n > 1)
       return n * fatorial
    else
       return 1
    end

n = gets.to_i ()
fat = fatorial (n)
array2 = n ==1
array2 << array1

puts "Os números armazenados são: #{n} + #{array2}"
end
    
asked by anonymous 13.05.2018 / 00:38

1 answer

1

First, your fatorial function has 2 problems:

  • the last end is missing at the end to close it
  • When the number is greater than 1, you should call n * fatorial(n - 1) (because calling only fatorial , without passing parameters, causes an error, because the function expects a number as a parameter). This follows the mathematical definition, for example, 5! = 5 * 4! - generalizing, n! = n * (n - 1)! (the factorial of a number is this number times the factorial of this number minus 1). Therefore, the expression must be n * fatorial(n - 1) . If you do not pass any parameters (just type fatorial , as you did), the function has no way of knowing which number to use.

Then it would look like this:

def fatorial (n)
    if (n > 1)
       return n * fatorial(n - 1)
    else
       return 1
    end
end

The last end should not be after puts , but soon after if-else , because that is where the fatorial function ends.

As for the arrays, I do not quite understand what you want to do. You are creating array1 , filling in several numbers and then you do not use these numbers at all (just to copy them to array2 ).

You are also putting the factorial result in the fat variable, but then you do not use this variable at all.

If you want to create a array2 containing the result of the factorial of the numbers that are in array1 (and this is my guess since it is not clear what you want ), then you can do something like this:

array2 = []
# para cada número em array1, calcular o fatorial e armazenar em array2
array1.each { |n|  array2.push(fatorial(n)) }

Or:

array2 = array1.map { |n| fatorial(n) }

With this, each number of array2 corresponds to the factorial of the number that is in the corresponding position in array1 . For example, if array1 has the numbers [2, 3, 7] , array2 will have their respective factorials ( [2, 6, 5040] ).

If this is not what you want, edit your question by better explaining what you are trying to do, examples of input and output (what you want and what the program returns), error messages that appear, etc.

    
14.05.2018 / 14:11