Advertisement
Guest User

primes in range

a guest
Aug 16th, 2015
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.79 KB | None | 0 0
  1.  class Primes
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.  
  6.             int counter = 0; // how many primes we have found so far
  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 (counter <= position3) // counter <= 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.                     counter++; // the prime numbers we have found so far are incremented by one
  30.                     if (counter == position1 || counter == position2 || counter == position3) // if we have found he let's say 24th number, the counter will be 24 so we will print the prime number on position 24
  31.                     {
  32.                         Console.WriteLine(number);
  33.                     }
  34.                 }
  35.  
  36.                 number++; // go to the next number to check if it's prime again
  37.             }
  38.         }
  39.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement