From 7dbdc4d61f1223454e8b50baf5e9a6dbf3e47979 Mon Sep 17 00:00:00 2001 From: brittanynb Date: Wed, 2 Mar 2016 20:22:52 -0500 Subject: [PATCH] code from the demo! --- factorial.m | 8 +++++--- factorialTest.m | 8 ++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/factorial.m b/factorial.m index 323e397..6d8ac69 100644 --- a/factorial.m +++ b/factorial.m @@ -1,9 +1,11 @@ function [ result ] = factorial( n ) %factorial Computes the factorial of n - if n == 0 - result = 1 + if n < 0 + result = nan; + elseif n == 0 + result = 1; else - result = n * factorial(n -1) + result = n * factorial(n - 1); end end diff --git a/factorialTest.m b/factorialTest.m index 7d6385e..498ba0e 100644 --- a/factorialTest.m +++ b/factorialTest.m @@ -7,3 +7,11 @@ facOfTen = 10*9*8*7*6*5*4*3*2*1; assert(facOfTen == factorial(10), 'factorial(10) should be 3628800'); +%% Test negative +assert(isnan(factorial(-1)), 'factorial of a negative should be nan'); + +%% Test invariant +assert(factorial(10) == 10 * factorial(9), 'factorial recursion'); + + +