MartinPaunov

07. Primes in Given Range

Feb 4th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.37 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Numerics;
  4. using System.Text;
  5.  
  6. namespace CSharpDemos
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             int startNum = int.Parse(Console.ReadLine());
  13.             int endNum = int.Parse(Console.ReadLine());
  14.  
  15.             if (startNum > endNum)
  16.             {
  17.                 Console.WriteLine("(empty list)");
  18.             }
  19.  
  20.             List<int> primes = new List<int>(PrimesInRange(startNum, endNum));
  21.  
  22.             string result = string.Join(", ", primes);
  23.  
  24.             Console.WriteLine(result);
  25.         }
  26.  
  27.         static List<int> PrimesInRange(int startNum, int endNum)
  28.         {
  29.             List<int> result = new List<int>();
  30.  
  31.             for (int i = startNum; i <= endNum; i++)
  32.             {
  33.                 if (i < 2)
  34.                 {
  35.                     continue;
  36.                 }
  37.                 bool isPrime = true;
  38.                 for (int j = 2; j <= Math.Sqrt(i); j++)
  39.                 {
  40.                     if (i % j == 0)
  41.                     {
  42.                         isPrime = false;
  43.                         break;
  44.                     }
  45.                    
  46.                 }
  47.                 if (isPrime)
  48.                 {
  49.                     result.Add(i);
  50.                 }
  51.             }
  52.             return result;
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment