/* Problem 6--The Spiral of Primes After using the same code we used in Problem 2 to compute the primes, you can use mathematical formulas to figure out the leg of the spiral that contains that position, and the index of the prime at that location. It helps to recall that 1+2+...+n = n(n+1)/2 */ #include #include FILE *in, *out; int Primes[10000], Pct; int main (int argc, char **argv); void GetPrimes (void); int main (int argc, char **argv) { int x,y, cs=0,p; in = fopen ("prob6.in","r"); out = fopen ("prob6.out","w"); GetPrimes(); while (1) { fscanf (in,"%d",&x); if (x==-999) break; fscanf (in,"%d",&y); /* compute the index */ if (y >= 0 && x >= -y && x <= y) p = y*(4*y-1)-x; else if (x <= 0 && y >= x && y <= -x) p = 4*x*x-x-y; else if (x >= 0 && y >= -x+1 && y <= x) p = (2*x-1)*(2*x-1)+x-1+y; else p = y*(4*y-3)+x; fprintf (out,"Case %d: The prime at location (%d,%d) is %d.\n\n",++cs, x,y,Primes[p]); } fclose (in); fclose (out); return EXIT_SUCCESS; } /* GetPrimes puts all primes up to 10000 into an array.*/ void GetPrimes (void) { int i, p; for (i = 2; i <=10000; i++) { int IP = 1; /* check up to the square root */ for (p = 0; p < Pct && Primes[p]*Primes[p]<=i; p++) if (i%Primes[p]==0) {IP = 0; break;} if (IP) Primes[Pct++] = i; } }