CSharp · Console
// Write a function that finds the smallest divisor d>1 of given integer n>1.
using System;
using System.Diagnostics;
public class Program
{
static public int SmallestDivisor(int n)
{
Trace.Assert(n > 1);
return SmallestDivisorInRange(n, 2);
}
// Input: 1 < d <= n
// Returns the smallest divisor of n in range d..n
// Completion: n - d is not negative and decreases by 1 in each nested call
static public int SmallestDivisorInRange(int n, int d)
{
if(n % d == 0)
return d;
// d != n => d < n => d+1 <= n
return SmallestDivisorInRange(n, d + 1);
}
static public void Main()
{
for(int n=2; n < 32; n++)
Console.WriteLine("Smallest divisor of {0} is {1}", n, SmallestDivisor(n));
}
}