0

I have to write a function in C for my homework. Given the functions is_prime(n) and nth_prime(n),the first returning 1 if n is prime(or 0 if it's not) and nth_prime returning the nth prime number, i have to write the function next_prime(count) which counts the time it's called and then returns the "count-th" number prime. count must be a static unsigned int variable. If n=0 (n is given with a scanf ),count value must be reset to 0,and the function returns the first prime number,2.
I can't use structures,arrays or recursion. I'm new to coding,and I don't know what to do. I use Visual Studio 2010 and I have to compile it as ISO C89(ANSI C). The functions must be written in a library file,the only thing that's going to be evaluated,so I can't use a count++ in the main () function. Here's what I've done so far.

unsigned int next_prime( unsigned int count ) {
    if( count == 0 ) {
        if ( n=!0 ) {                       
            return nth_prime( count );
            count++;
        } else {
            count = 0;
            return 2;
        }      
    } else {    
        if ( n=!0 ) {                       
            return nth_prime( count );
        } else {
            count = 0;
            return 2; 
        }       
    }
}   
4

1 回答 1

0

Here is a function that will meet your question:

/* the function next_prime(count) */
unsigned int next_prime(unsigned int count) {
    /* avoid "unused parameter" warning */
    (void)count;
    /* introduce this block because defining the variable count here will read to an redeclaring error */
    {
        static unsigned int count = 0;
        int n = -1;
        /* n is given with a scanf */
        scanf("%d", &n);
        /* if n=0 */
        if (n == 0) {
            /* count value must be reset to 0 */
            count = 0;
            /* return the first prime number, 2 */
            return 2;
        } else {
            /* count the time it is called */
            count++;
            /* return the "count-th" prime number */
            return nth_prime(count);
        }
    }
}
于 2015-10-25T11:47:22.653 回答