You are here:

- Home
- Computing/Technology
- C/C++
- C++
- prime numbers

Advertisement

im given an assignment in which the user is to enter the number of prime numbers to be displayed and the computer should display that.for example the if user wishes to see first ten prime numbers then the computer should display first ten prime numbers...i know how to check if a number is prime or not and even to display prime numbers less than a number but to display first five prime numbers for example is beyond me...can you help me with that??

> i know how to check if a number is prime

if you know that, the rest is trivial.

a. you would be able to write a function

bool is_prime( int number ) ;

which returns true if number is prime, false otherwise.

b. now write a function

int next_prime( int number ) ;

which returns the next prime number just higher than number.

this is easy; to get the result into number:

keep incrementing number in a do-while loop

till is_prime(number) returns true.

c. if you want to print out the first N prime numbers,

void print_n_primes( int N )

{

int number = 2 ; // first prime number

for( int count = 0 ; count < N ; ++count )

{

std::cout << number << '\n' ;

number = next_prime( number ) ;

}

}

d. once you have got this working correctly,

think about how you can make the functions

is_prime and next_prime more efficient.

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

about 15 years or so**Education/Credentials**

post graduate engineer