Problem 2-4

CSharp · Console

/Program.cs

// Write a program that inputs integer number n>1 and 
// prints “prime” if it is prime or 
// one of its possible factorizations if it is not prime.

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 > 1);
		
		int d = 2;
		// invariant: n has no divisors less than d (except 1)
		while (n % d != 0 && d * d <= n)
		{
			// d is not a divisor of n
			d++;
		}
		// n has no divisors less than d (except 1)
		// d is divisor of n or d exceeds sqrt(n)
		if(n % d == 0)
			Console.Write(n.ToString() + " = " + d + " * " + n / d);
		else
			Console.Write(n.ToString() + " is prime");
    }
}
;