...

View Full Version : Can I improve my code?



Advancedkill
07-27-2008, 03:42 PM
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!



#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
}
}

oracleguy
07-27-2008, 08:12 PM
You shouldn't be using global variables, pass them to your setup function from main instead.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum