Generation of Prime Numbers in C++

0
212
Generating Prime Numbers in C++
Operator overloading in C++

Implementing the 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. }

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 Generation of Prime Numbers Generation in C++.

Generating Prime Numbers in C++
Operator overloading in C++

Leave a Reply