StefanSinapov
2/25/2015 - 8:33 PM

1-Primes-In-An-Interval

using System;
using System.Collections.Generic;

namespace _1_Primes_In_An_Interval
{
    class EntryPoint
    {
        static void Main(string[] args)
        {
            // you can check it here: http://primes.utm.edu/lists/small/1000.txt
            try
            {
                Console.WriteLine("Primes [1100, 1200]: {0}", string.Join(", ", PrimesInInterval(1100, 1200))); //1103   1109   1117   1123   1129   1151   1153   1163   1171   1181   1187   1193 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                Console.WriteLine(string.Join(", ", PrimesInInterval(200, 100))); 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public static List<int> PrimesInInterval(int from, int to)
        {
            if (from < 0 || to < 0 || to < from)
            {
                throw new ArgumentException("invalid input");
            }

            var primesList = new List<int>();

            for (int num = from; num <= to; num++)
            {
                bool prime = true;
                for (int div = 2; div <= Math.Sqrt(num); div++)
                {
                    if (num % div == 0)
                    {
                        prime = false;
                        break;
                    }
                }
                if (prime)
                {
                    primesList.Add(num);
                }
            }
            return primesList;
        }
    }
}