Generating Prime Numbers in C++

0
610
Prime Numbers Generation in C++
Generation of Prime Numbers in C++

Now implementing this logic of Prime Numbers into our c++ code, we need simple for loops and conditional statements. This is very easy to implement and print Prime Numbers upto 1000. Lets have a look at the following code:

  1. //Prime Numbers generation in C++
  2. //Using for loops and conditional structures
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.     int a = 2;       //start from 2
  9.     long long int b = 1000;     //ends at 1000
  10.  
  11.     for (int i = a; i <= b; i++)
  12.     {
  13.  
  14.      for (int j = 2; j <= i; j++)
  15.      {
  16.         if (!(i%j)>>(i!=j))    //Condition for not prime
  17.             {
  18.                 break;
  19.             }
  20.  
  21.         if (j==i)             //condition for Prime Numbers
  22.             {
  23.                   cout << i << endl;
  24.  
  25.             }
  26.      }
  27.     }
  28. }

Now lets explain this code, first of all we defined two variables that defined our limits upto which we are going to print Prime Numbers. The most important thing is using the “conditional statement ” inside the nested for loops. We used a condition that if the variables inside the loop do not have true modulus and both the variables are not equal then break, otherwise if both variables are equal then it is a Prime Number, and print it. And its all about Generating Prime Numbers in C++.

Prime Numbers Generation in C++
Generation of Prime Numbers in C++

Leave a Reply