Problem 3-2

CSharp · Console

/Program.cs

/*
  Consider a monotonic sequence of natural numbers
  where each number k occurs k times: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 etc.
  Write a program that inputs integer n>0 and prints n-th element of this sequence. 
*/					
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()
	{
		int n = InputInt("n");
		Trace.Assert(n > 0);
		
		// Inductive extension:
		int i   	= 1;	// index of the last element i>0
		int last    = 1;	// last element of the sequence
		int count	= 1;    // number of times the last element occurs 
		// invariant: inductive extension definition and i<=n
		while(i != n)
		{
			i++;
			if(last==count)
			{
				last = count + 1;
				count = 1;
			}
			else
			{
				count++;
			}
		}
		// i==n => last==n-th element
		Console.WriteLine("{0}-th element is {1}", n, last);
	}
}
;