Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 2 of 2
Thread: Can I improve my code?

07272008, 02:42 PM #1
 Join Date
 May 2006
 Posts
 16
 Thanks
 0
 Thanked 0 Times in 0 Posts
Can I improve my code?
Hi
I made a program to answer question 1 from this paper
http://www.olympiad.org.uk/papers/20...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[numeveni]==1)) { //If two numbers add to make numeven *i+(ni)=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 nonprimes 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 } }
07272008, 07:12 PM
#2
 Join Date
 Jun 2002
 Location
 USA
 Posts
 9,074
 Thanks
 1
 Thanked 328 Times in 324 Posts
You shouldn't be using global variables, pass them to your setup function from main instead.
OracleGuy