Created
May 7, 2016 07:08
-
-
Save serabakpak/26a8273e2ccb74604f937b14f4104996 to your computer and use it in GitHub Desktop.
https://repl.it/Br5o/558 created by serabakpak
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 method that takes an integer `n` in; it should return | |
# n*(n-1)*(n-2)*...*2*1. Assume n >= 0. | |
# | |
# As a special case, `factorial(0) == 1`. | |
# | |
# Difficulty: easy. | |
def factorial(n) | |
total = n | |
m = 1 | |
if n == 0 | |
return 1 | |
end | |
while n >= 0 and (n - m) > 0 | |
total = total * (n - m) | |
m += 1 | |
end | |
total | |
end | |
puts(factorial(3)) | |
# These are tests to check that your code is working. After writing | |
# your solution, they should all print true. | |
puts("\nTests for #factorial") | |
puts("===============================================") | |
puts( | |
'factorial(0) == 1: ' + (factorial(0) == 1).to_s | |
) | |
puts( | |
'factorial(1) == 1: ' + (factorial(1) == 1).to_s | |
) | |
puts( | |
'factorial(2) == 2: ' + (factorial(2) == 2).to_s | |
) | |
puts( | |
'factorial(3) == 6: ' + (factorial(3) == 6).to_s | |
) | |
puts( | |
'factorial(4) == 24: ' + (factorial(4) == 24).to_s | |
) | |
puts("===============================================") |
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
ruby 2.2.0p0 (2014-12-25 revision 49005) | |
>>> (repl):42: syntax error, unexpected end-of-input, expecting keyword_end | |
puts("===============================================") | |
^ | |
>>> => nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment