Skip to content

Instantly share code, notes, and snippets.

@dstavis
Created December 15, 2013 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstavis/7979797 to your computer and use it in GitHub Desktop.
Save dstavis/7979797 to your computer and use it in GitHub Desktop.
Exercise 21: Implement the factorial function
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.
------------CODE-------------
def factorial(n)
if n == 0
return 1
end#if
counter = 1
array = []
unless counter > n do
array.push counter
end#unless
factorial = 0
array.each do |value|
if factorial == 0
factorial = value
else
factorial = factorial * value
end#else, if
end#each
return factorial
end#def
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment