What you are looking for is Unit Tests, not Code Contracts.
Typically, tests such as if n=0, then f(n) = 1 and if n=3, then f(n) = 6 are test cases that should be expressed as unit tests.
In your case, I think that the appropriate message condition would look like "Result Always> = 1." And nothing more.
Assuming your factor class looks something like this:
public class Factorial { public int Compute(int n) { if (n == 0) return 1; return n * Compute(n - 1); } }
suitable Unit Test written with the NUnit Framework :
[TestFixture] public class FactorialTests { [TestCase(0, 1)] [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(7, 5040)] [TestCase(10, 3628800)] public void Compute_ReturnsCorrectResult(int n, int expectedResult) { var sut = new Factorial(); Assert.AreEqual(expectedResult, sut.Compute(n)); } }
Update (after comments)
The result of the check> = 1 does not completely determine the algorithm.
I do not think that the work of Code Contract is to describe the algorithm in detail. the algorithm is specified by the method.
If Code Contract was complex logic similar to the method itself, then I think we will need a code contract to verify that the Code Contract is performing the correct checks. This obviously leads to infinite recursion.
I did not expect n*(n-1)*...*1 be accepted by the compiler. But some general range operator in the LINQ-matched way will undoubtedly be a complement to gread. From (n) .To (1) .Product () or From (n) .To (m) .Sum ()
If there was such a form of factorial expression (and probably is), you could use it in your code, and not in Code Contracts.
Update 2
Just for fun, I found a LINQ way to calculate Factorials:
Enumerable.Range(1, n == 0 ? 1 : n).Aggregate((a, i) => a * i);