Prime number series – CSKC
Sign In

Search

Code Learning #CPP#2429    siteicon   siteicon  

Prime number series

Print a series of prime numbers up to predefined number of terms..

Learning Objectives

  • Deducing a prime number within a term printing series and then keep increasing the number till another prime is found. Once found series term is equated to it and printed.

Source Code

TC++ #2429

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Alternate (?) :   Related ( ? ) :

Code Understanding

int no_of_terms=50; //Number of terms to be printed has been given here
int term,n=2; 
term variable declared and another variable n to use for prime testing has been initialised as 2. The initialisation with 2 is done because we know that any number will definitely be divisible by 2 and further divisibility testing has to begin with 2.

for(int tc=1;tc<=no_of_terms;++tc) //Loop for term counting from 1 to no_of_terms
{
while(1) //This endless loop runs till it is broken by finding of a prime number.
{
int dc=0; //dc stores divisor count, moment it increases means number is not prime.
for(int i=2;i<=n/2;i++)
This internal loop begins from 2 and goes up to half of the number value. Any non prime number will definitely have at least one divisor which is 2 or any greater number up to the half of number.
if(n%i==0) dc++; //If n is divisible by any number from 2 to half of number then it is not prime
if(dc>0) n++; //If there is a divisor then one continues loop for checking the other number.
else break; //Else it must be a prime so come out of loop
}
term=n++; //The term is equated current number and it is increased for the other iteration later.
cout<<term<<” “; //The given prime number is printed and the series continues.
}

Notes

  • Prime number series can be very taxing for even a super computer. Here we are printing just 50 terms. However you may give number of terms as 10,00,000. You will find that computer the may take many minutes or some time hours to keep printing this series.
  • The challenge of finding largest prime number is a mathematicians delight. It is some times said that the largest prime number challenge will remain active till the mathematicians remain anywhere on this planet. You may be interested to know more about it from
    https://www.mersenne.org/


Suggested Filename(s): prime-series.cpp



Share

Created: 10-Jan-2018 17:16 | Updated: 15-Sep-2018 13:18|