Monday, January 25, 2021
Home C / C++ Generation of Prime Numbers in C++

Generation of Prime Numbers 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;
  6. int main()
  7. {
  8.     int a = 2;       //start from 2
  9.     long long int b = 1000;     //ends at 1000
  11.     for (int i = a; i <= b; i++)
  12.     {
  14.      for (int j = 2; j <= i; j++)
  15.      {
  16.         if (!(i%j)>>(i!=j))    //Condition for not prime
  17.             {
  18.                 break;
  19.             }
  21.         if (j==i)             //condition for Prime Numbers
  22.             {
  23.                   cout << i << endl;
  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++.

- Advertisment -

Most Popular

Android Webview Tutorial With Example | How to Use Webview in Android

Android Webview Tutorial With Example Have you seen an Android app displaying Web content using Webview. This Android Webview Tutorial is about integrating Webview using Android Studio....

Student Registration Project in PHP

In this Student Registration Project we are providing a form in simple html to the student and that form sends the data to "student.php"...

Java GUI Calculator Source Code

Here we have a Java GUI Calculator Source Code for you in which a Java GUI calculator has been created using "swing" and "awt". The calculator has...

Numeric Array in PHP

Numeric arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero....