C++ Prime CHecker

Hi
I am a beginner in C++ and would like someone to give me an idea or push me in the right direction of how to solve this question , It is related to classes

Design and implement a class called PrimeChecker to check if a number is
prime. The class stores an array of consecutive primes. It uses this array
to check if a given number is prime. To simplyfy the excercise the array
will store at most 1000 prime numbers. The class has the following public
methods:
(a) Constructor
The array to store up to 1000 primes is created and the prime number
’2’ and ’3’ are stored in side the array.
(b) Destructor
(c) IsPrime() which returns a boolean and takes a parameter which is
an integer.
Note: Whether a number n is prime can be checked by testing divis-
ibility of all primes from 2 to the √n.
Check if the array stores all needed prime numbers and extend place
more consecutive prime numbers into array if needed.
(d) printAllKnownPrimes() which prints all the primes stored in the ar-
ray using cout.

Thank you in advance =)
You should start by reading up on classes:
http://www.cplusplus.com/doc/tutorial/classes.html

The assignment wants you to create a class with specific properties so you should try that yourself, and if you have problems ask (specific) questions.
(c) IsPrime() which returns a boolean and takes a parameter which is
an integer.


Many students have already asked for this, try surfing a bit on this site
Last edited on
I know you only have to check prime numbers and then only up to the square root of the new number being tested. I think there's a simple way to approximate a square root that only requires a fraction of the machine cycles.
Prime number calculation algorithms are so hideously inefficient anyway that the extra overhead to compute a square root is insignificant. Just call sqrt().

As long as you don't fall into the trap that everyone else falls into:

1
2
for( int i = 2; i <= sqrt( n ); ++i )
// ... 


which basically forces the compiler to generate code to call sqrt() every time through the loop.

Better is

1
2
3
int sqrt_n = sqrt( n );
for( int i = 2; i <= sqrt_n; ++i )
// ... 

Topic archived. No new replies allowed.