Created
December 15, 2013 23:24
-
-
Save dstavis/7979797 to your computer and use it in GitHub Desktop.
Exercise 21: Implement the factorial function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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