Skip to content

Instantly share code, notes, and snippets.

@kmandreza
Created January 4, 2013 03:05
Show Gist options
  • Select an option

  • Save kmandreza/4449593 to your computer and use it in GitHub Desktop.

Select an option

Save kmandreza/4449593 to your computer and use it in GitHub Desktop.
Write a factorial method which takes as its input a non-negative integer and calculates the factorial of that number. The factorial of a number is the product of all integers from 1 up to that number. For example: factorial(5) == 5 * 4 * 3 * 2 * 1 == 120 The factorial of 0 is defined to be 1. See the Wikipedia article on the factorial for more i…
def factorial(n)
result = 1 # you need somewhere to store the result, and since this is multiplication, you can't start at 0.
#THIS HAS TO BE OUTSIDE THE LOOP. Otherwise everytime it goes to the next i element result will go back to being 1.
n.downto(1) do |i|
result = result * i # here result and i are multiplied first, then the result is assigned to the result variable. Let me know if this is confusing.
end
# now, we've looped through all of the numbers and multiplied them, but the loop does not return anything.
return result # this will return the result that we ended up with after looping or iterating through.
end
# or
def factorial(n)
result = 1
n.downto(1) do |i|
result *= i # this is shorthand for result = result * i
end
result #we don't need the return, ruby automatically returns the value that is the last part of a method
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment