Problem 3-3

CSharp · Console

/Program.cs

// Write a program that inputs integer n>0 and calculates
// 1! + 2! + 3! +… + n!

using System;
using System.Diagnostics;
					
public class Program
{
	public static int InputInt(string prompt)
	{
		Console.Write("Enter " + prompt + ": ");
		return Convert.ToInt32(Console.ReadLine());
	}
	
    public static void Main(string[] args)
    {
        int n = InputInt("n");
		Trace.Assert(n > 0);
    	
        int r = 1;
		int i = 1;
		int q = 1;
		// invariant: r=i! and q=1!+...+i! and 1<=i<=n  
		while (i<n)
		{
			// r = i! and i<n
			i += 1;
			// r = (i - 1)! and q = 1!+...+(i-1)! and i<=n
			r *= i;
			// r = (i - 1)*i = i! and q = 1!+...+(i-1)! and i<=n
			q += r;
			// r = i! and q = 1! +...+ i! and i<=n
		}
		// r = i! and q = 1! + ... + i! and i=n => q = 1! + ... + n!
		Console.Write("...+{0}! = {1}", n, q);
    }
}
;