Can I improve my code?

Joined
Jul 27, 2008
Messages
3
Reaction score
0
Hi

I made a program to answer question 1 from this paper

http://www.olympiad.org.uk/papers/2008/bio/round_one.html

I used a "sieve of eratosthenes". Just wondering if there was anything that I could do better.

Thanks!

Code:
#include <stdio.h>

int MAXINPUT=10000;
int primes[10000];

void set_up_table_of_primes();

int main()
{
    extern int MAXINPUT;
    extern int primes[10000];   
    
    int numeven;
    printf("Type in your even number between 4 and 10000 inclusive:\n");
    scanf("%d", &numeven);  
  
    set_up_table_of_primes();

    int howmany = 0;
    int i = 0;

    if (numeven==4) {howmany++;} //If 4 was entered, howmany++

    for (i=3; i<=numeven/2; i+=2) //Use odd primes to find answer
    {  
        if ((primes[i]==1)&&(primes[numeven-i]==1))
        {
        //If two numbers add to make numeven *i+(n-i)=n* and are prime
            howmany++;
            printf("howmany = %d\n", howmany);
        }
    }

    printf("%d can be expressed as the sum of primes in %d ways\n",numeven, howmany);
    printf("finish\n");
    return 0;
}

void set_up_table_of_primes()
{
//Sieve of Eratosthenes

    extern int MAXINPUT;
    extern int primes[10000];
    int i, p, j;

    for (i=0; i<MAXINPUT; i++)
    {
    //everything provisionally prime
        primes[i] = 1;
    }

    printf("primes[15] = %d", primes[15]);

    primes[0] = primes[1] = 0; //0 and 1 are not prime
    p = 2;
    int flag=0;

    while (flag==0)
    {
    //Here we use a sieve of Eratosthenes to make all non-primes zeroed and leave primes as 1

        while (primes[p] == 0) {p++;} //find next prime
       
        if (p*p > MAXINPUT)
        {
        //Return to main function when done
            return;
        }

        for (j=2*p; j<10000; j=j+p)
        {
        //multiples of p are not prime either
            primes[j] = 0;
        }

        if(primes[p]==1) {p++;} //Move onto next prime number
    }
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,001
Latest member
Kendra00E1

Latest Threads

Top