Advertisement
Guest User

primes in range with list

a guest
Aug 16th, 2015
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1.    class Primes
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.  
  6.             List<int> primes = new List<int>(); // we keep here all primes from the first one to the 251th
  7.             int number = 2; // the number we start from
  8.  
  9.             int position1 = 24; // could be read from console
  10.             int position2 = 101; // could be read from console
  11.             int position3 = 251; // could be read from console
  12.  
  13.             while (primes.Count <= position3) // primes list count <= maxNumberFromInput e.g. 251
  14.             {
  15.                 bool isCurrentNumberPrime = true; // assert the number is prime, until we find the opposite
  16.  
  17.                 for (int divider = 2; divider <= Math.Sqrt(number); divider++)
  18.                 {
  19.                     if (number % divider == 0) // if the number is divisble to any number from 2 to its root, it's certainly not prime
  20.                     {
  21.                         isCurrentNumberPrime = false;
  22.                         break; // we have determined that the number is not prime, we don't need to try to divide to any number anymore. Exit the loop
  23.                     }
  24.                 }
  25.  
  26.  
  27.                 if (isCurrentNumberPrime) // if the number hasn't divided to any number from the previous loop, the boolean variable will stay "true"
  28.                 {
  29.                     primes.Add(number); // add the already determined prime number to our primes collection
  30.                 }
  31.  
  32.                 number++; // go to the next number to check if it's prime again
  33.             }
  34.  
  35.             Console.WriteLine(primes[position1 - 1]);
  36.             Console.WriteLine(primes[position2 - 1]);
  37.             Console.WriteLine(primes[position3 - 1]);
  38.             Console.WriteLine("----");
  39.             Console.WriteLine(primes[128]); // for sanity check let's try to find thr 127th prime
  40.         }
  41.  
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement