Thursday, 15 October 2015

Find Smallest and Largest Factor of a Number using Single for loop in C#

using System;
class Program
{
    static void Main()
    {
        int i, j;
        int smallest, largest;
        smallest = largest = 1;
        Console.WriteLine("Enter a Number for Factor");
        int Number = int.Parse(Console.ReadLine());
        for (i = 2, j = Number / 2; (i <= Number / 2) && (j >= 2); i++, j--)
        {
            if ((smallest == 1) && (Number % i) == 0)
            {
                smallest = i;
            }
            if ((largest == 1) && (Number % j) == 0)
            {
                largest = j;
            }
        }
        Console.WriteLine("{0} is the smallest and {1} is the Largest factor of {2}",smallest,largest,Number);
    }
}

No comments:

Post a Comment