On Tue, 7 Nov 2006

http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:

>

> i need to develop a code that finds a prime right number between 2 and

> 100000. and print one line of text that indicates if the int. is right

> prime. i am in beginning programing so complex is complicated. we are

> on a functions chapter. i am usung the square root to find the prime.

> so far i have accomplished this but i cant fgure how to divide this by

> ten so i can find the right prime. i am using c.
Is "right prime" different from "prime"?

> #include <stdio.h>

> #include <math.h>

>

> int slowPrime(int); //function prototype

>

> int main()

> {

> int x; // loop counter
Your indentation got messed up by your newsreader; I've restored proper

indentation below.

> int count = 0; // total numbers of prime found

> long prime;

>

> printf_s("The prime numbers from 1 to 10000 are:\n" );
'printf_s' should be 'printf', of course.

> for ( x = 2; x <= 2147483647 ; x++ )
When will this loop terminate if INT_MAX (the maximum possible value of

an 'int') is 32767? What if INT_MAX is 2147483647? Remember, all ints

are by definition at most INT_MAX --- there are no ints greater than

INT_MAX.

Also, you might consider how many even primes there are, and then

modify your program accordingly.

> {

> if (Prime(x)) {
I haven't seen a prototype for 'Prime' yet. You should put declarations

for all your functions (except, usually, 'main') at the top of your

program, or at least somewhere prior to their first use.

> ++count; // count and print prime

> //printf_s("%10d", x );

>

> if (count % 10 == 0) // new line after 10 values diplayed

> printf_s( "\n" );

> } // end for

> } // end if

>

> printf_s("%d prime numbers were found\n", count);

> return 0; // indicate successful termination

> } // end main

>

> int isRightPrime( int n ) // slow prime returns 1 if n is prime

> {

> int i; // loop counter

>

> for (i=2; i <= (int)sqrt(n); i++) {
As before, consider that there is only one even prime. Look up the

"Sieve of Eratosthenes", if you haven't yet.

Also notice that "i <= (int)sqrt(n)" is basically testing the same

thing as "i*i <= n". Which of those two expressions do you think would

execute faster on a real-world computer?

> if (n % i == 0)

> return 0;

> } // end for

>

> return 1;

> } // end function prime
Where's the definition of 'Prime'? I also notice that the function

'isRightPrime' was never used.

> i know this can not be as complicated as i have made it.
Modulo all those elementary errors and bugs, you've got the basic

naive algorithm for prime testing. There's nothing wrong with using it

for tiny numbers (say, numbers less than 2^32). For bigger numbers,

there are faster algorithms.

-Arthur