From e4fb9211bea71d37c0f2b4114a5811d02d224aa4 Mon Sep 17 00:00:00 2001 From: Sopheary Chiv Date: Wed, 10 Apr 2019 23:09:39 -0700 Subject: [PATCH 1/2] passed tests --- lib/factorial.rb | 16 +++++++++++++--- specs/factorial_spec.rb | 12 ++++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/factorial.rb b/lib/factorial.rb index 6a4a408..e04816e 100644 --- a/lib/factorial.rb +++ b/lib/factorial.rb @@ -1,6 +1,16 @@ # Computes factorial of the input number and returns it -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(1) +# Space complexity: O(1) def factorial(number) - raise NotImplementedError + return 1 if number == 0 + return 1 if number == 1 + raise ArgumentError if number == nil + fact = 1 + index = 1 + while index < number + fact *= (index + 1) + index += 1 + end + + return fact end diff --git a/specs/factorial_spec.rb b/specs/factorial_spec.rb index de28055..89067ab 100644 --- a/specs/factorial_spec.rb +++ b/specs/factorial_spec.rb @@ -1,6 +1,6 @@ -require 'minitest/autorun' -require 'minitest/reporters' -require_relative '../lib/factorial' +require "minitest/autorun" +require "minitest/reporters" +require_relative "../lib/factorial" describe "factorial" do describe "basic tests" do @@ -8,6 +8,10 @@ factorial(5).must_equal 120 end + it "factorial(3) = 6" do + factorial(3).must_equal 6 + end + it "factorial(7) = 5040" do factorial(7).must_equal 5040 end @@ -17,7 +21,7 @@ describe "edge cases" do # if the parameter is an object, check for nil it "nil object is not an integer" do - proc {factorial(nil)}.must_raise ArgumentError + proc { factorial(nil) }.must_raise ArgumentError end it "factorial(0) = 1" do From 2bce238686a21ea18f81505e9f6b5a456957e71b Mon Sep 17 00:00:00 2001 From: Sopheary Chiv Date: Wed, 10 Apr 2019 23:13:58 -0700 Subject: [PATCH 2/2] changed answer to O(n) --- lib/factorial.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/factorial.rb b/lib/factorial.rb index e04816e..d04b494 100644 --- a/lib/factorial.rb +++ b/lib/factorial.rb @@ -1,5 +1,5 @@ # Computes factorial of the input number and returns it -# Time complexity: O(1) +# Time complexity: O(n) where n is the number # Space complexity: O(1) def factorial(number) return 1 if number == 0