Title: Program efficiency and
computing prime numbers
Topics covered: Modular
Programming and Functions
Purpose: Gain experience writing and
using functions. Analyzing program efficiency.
Description: An integer is said to be
prime if it is divisible by only 1 and itself. For example. 2,3,5,7, and 11 are
prime, but 4,6,8,9, and 10 are not. You are to write a function that determines
whether a number (given as a parameter) is prime or not. Your function should
return value 1 if the number is prime, and return value 0 if the number is not
prime. Here is a function prototype: int TestPrime(long).
Write a program
that uses this function TestPrime to print out all prime numbers between 1 and
10,000. Include in your code function calls to the <ctime> library, so
that you can determine how long your program takes to complete. See the following
example:
#include
<iostream>
using namespace std;
#include <ctime>
int TestPrime( long );
int main()
{
long Starttime = time(0);
cout << "\nThe starting time is " << Starttime;
for (long i = 1 ; i
< 10000; i++)
if (TestPrime(i) ==1)
cout << i << "
\t ";
long Endtime = time(0);
cout <<"\n End time is
" << Endtime;
long Durationtime = Endtime – Starttime;
cout <<"\n The total length
of execution time is" << Durationtime << endl;
}
Record the time
taken. You may modify the number of integers to test (higher or lower) so that
the computing time is reasonable on your machine (e.g., not 0 and not too
large).
Now let us look at
the efficiency issue. You will test if an integer N is prime by determining
whether there is an number less than N that will divide into N evenly (using
the mod % operation). Now think, is it necessary to check every number less
than N for divisibility? No, you need only check the numbers up to square root
of N. Why? Rewrite your TestPrime function to check divisibility only up to the
square root of N. Now run your program again to see if there is any performance
improvement. If time permits, test performance gains for different values including
100,000 and 1,000,000 and higher for the upper limit. What is the largest prime
number you can find before the lab is over?