Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions lib/factorial.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
# Computes factorial of the input number and returns it
# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n-1) which is simplified to 0(n) where n is the value of the number
# Space complexity: 0(1) because no additional space is being used in relation to the lenght of the input
def factorial(number)
raise NotImplementedError
raise ArgumentError if number.nil?
return 1 if number == 0 || number == 1
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice handling of base cases up front.


i = number
until i == 1
i -= 1
number = number * i
end
return number
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great solution! Maybe i could be renamed as factorial? It might make it easier to read.

end
2 changes: 2 additions & 0 deletions specs/factorial_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
require 'minitest/reporters'
require_relative '../lib/factorial'

Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new

describe "factorial" do
describe "basic tests" do
it "factorial(5) = 120" do
Expand Down