See this re-worked example. The goal was to more optimize the code and show some crash proofing, data validation, etc. ... for you to keep for future reference if needed ....
First you get the code working and tested out with some real test inputs ...
Then you look and see if some things can be 'optimized' a little (if you like.)
Here, one can skip over all even numbers, since we know in advance that they are not 'prime' ...
(They are other things that can be done to improve the code .... One only needs to divide by divisors up to (about?) the square root of the top number, for example ... Code can be very personal at times. Clear code is preferred by many, to tricky code, if the time gained is not really a big deal.)
One could simply test for all divisors in a loop ... but once we have established that a number is not prime, there is no further need to feed it test divisors, and we may then 'break' out of that loop.
Shalom,
David
CODE
/*
'C' all primes greater than 2,
up to, and including a 'top'
number that the user inputs.
The user may ask for another
'top' number to test repeatedly ...
A careful choice of variable names
may also assist solving a problem .
*/
#include <stdio.h>
void showPrimesUpTo( int num );
int main()
{
int c, max; /* 'c' is used as a character 'scratch' pad here */
for(;;) /* loop for ever ... until break or exit or return */
{
printf("Input 'top prime' number to test (greater than 1) : ");
scanf("%d", &max);
while( (c=getchar()) != '\n' ); /* 'flush' stdin buffer */
if (max < 2)
{
printf( "\nIs %d greater than 1 ?\n\n", max );
continue; /* from top of the for loop ... */
}
printf( "\nPrimes are 1 2 ...\n" );
showPrimesUpTo( max );
printf("\nMore y/n ? ");
c=getchar();
if ( c=='n' || c=='N' ) return 0;
while( (c=getchar()) != '\n' ); /* 'flush' stdin buffer */
}
}
void showPrimesUpTo( int topNum )
{
/*
A number IS 'prime' if it IS divisible by ONLY 1 and the
number ITSELF. Some times we may go like this { 1, 2, 3, 5, 7, 11 ... }
(So here ... NO need to divide by 1, 2, or self ...we need ONLY
to check ODD numbers beyond 2 to see if they divide with NO remainder ?
*/
/* 'j' is used as a counter, 'k' is used as a flag */
int testNum, i=0, j, k; /* i is used to limit numbers printed on a line */
/* only NEED to test ODD numbers; All EVEN beyond 2 are NOT prime. */
for(testNum = 3; testNum <= topNum; testNum += 2)
{
/* always 're-set' or 'initial' flags before each new iteration */
k=0;
/* this loop is to try every ODD number from 3 up to top as a divisor */
for(j = 3; j < testNum; j += 2)
{
if(testNum % j == 0)
{
/* Set k ... We have a divisor and testNum is NOT a prime. */
k=1;
break; /* So can EXIT INNER 'for loop' right NOW. */
}
}
/* When we reach hear, if k==0, then that 'testNum' was a prime. */
if(k == 0)
{
printf("%4d ", testNum);
if( ++i == 15 ) { i=0; printf("\n"); }
}
// end of inner 'trial divisor' loop
} // end of outer 'for testNum ...' loop
}
This post has been edited by David W: 15 Oct, 2008 - 11:10 AM