Copyright © Programs ++
Design by Dzignine
Wednesday, 7 March 2012

Prime number generation in C++

Numbers can become quite a huge mess when it comes to generating a particular type of series :p. Many number series such as prime numbers and the famous Fibonacci series are widely taught to C++ beginners. My previous post was related to Fibonacci series so i thought it be a good idea to write something on prime numbers.

Now, for those who don't really know :P, prime numbers are basically numbers that are only divisible by 1 and themselves.
For e.g 23 is a prime number as it is divisible only by 1 and itself. Some prime numbers are as follows :
2 3 5 7 11 13 17 19 23 31 37 on. Notice that most of the prime numbers greater that 2 are odd. This is also a
notable property of prime numbers.

However, the question is this ...HOW TO GENERATE THEM  ???? It seems that there is no exact formula to generate all the
prime numbers. But by using simple loops , we can generate them in C++. :)  The program given below shows how :

// Program to generate prime numbers in C++

#include <iostream>

int main()
     int max;
     // prompts the user to enter the range in which to generate
     std::cout<<" Enter the upper range ? : ";

     for (int n=2; n<max; n++) // main loop
          int flag = 0;
          // loop to check whether a numbers is prime or not
          for (int i=2; i<=n/2; i++)
               if ( n%i == 0 )
                    flag = 1;
               if ( flag == 0 )
                    std::cout<<" "<<n;
     } // end of main loop
     return 0;
} // end of main
------ OUTPUT ------

------ Programming advice and Tips ------

1 - There are numerous ways to generate prime numbers, you can find a lot of algorithms simply use our holy grail of search engines, GOOGLE. !!!

2 - Many algorithms use have different complexity and vary on speed, complexity and limitations. So choose what suits you best.

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better. 
------ Related Posts ------ 

1 : Fibonacci series in C++ : 
2 : Sieve of Eratosthenes algorithm to generate prime numbers ( for all programming languages ) :
3 : Prime Number Theorem :
4 : Checking whether a number is prime or non-prime :


  1. This code is frequently ask in any examination Check Number is Prime or not in C++ is very simple and easy to write. Using for loop and if else we can write this code. Your code is very simple and easy to understand. Thanks for sharing this article.


Comment Here....