01: #include<stdio.h>
02: #include<stdlib.h>
03: #include<math.h>
04: 
05: // #3
06: int *crivello(int);
07: 
08: int main(int argc, char **argv){
09: 
10:   // #1
11:   char nomefile[1000];
12:   printf("Inserire il nome di un file: ");
13:   scanf("%s", nomefile);
14: 
15:   // #2
16:   int n;
17:   FILE *fp = fopen(nomefile, "rb");
18:   // #1
19:   if(!fp)
20:   {
21:     perror("");
22:     exit(EXIT_FAILURE);
23:   }
24: 
25:   fread(&n, sizeof(int), 1, fp);
26:   fclose(fp);
27: 
28:   //printf("DEBUG: dal file ho letto %d\n", n);
29: 
30: 
31:   // #3
32:   int *primi = crivello(n);
33: 
34:   // #4
35:   printf("Numeri primi tra 2 e %d: ", n);
36:   for(int i = 0; i < (n - 1); ++i)
37:     if(primi[i])
38:       printf("%d, ", i + 2);
39:   printf("\b\b \n"); // magic trick to remove the last ','
40: 
41:   // #5
42:   sprintf(nomefile, "%d.dat", n); // generate filename
43: 
44:   fp = fopen(nomefile, "wb");
45:   if(!fp)
46:   {
47:     perror("");
48:     exit(EXIT_FAILURE);
49:   }
50: 
51:   for(int i = 0; i < (n - 1); ++i)
52:     if(primi[i])
53:     {
54:       int output = i + 2;
55:       fwrite(&output, sizeof(int), 1, fp);
56:     }
57: 
58:   fclose(fp);
59: 
60:   // #6 always mandatory freeing memory
61:   free(primi);
62: 
63: 
64:   return 0;
65: }
66: 
67: // #3
68: int *crivello(int n)
69: {
70:   // #3.a
71:   int *numeri = malloc((n-1)*sizeof(int)); // 2 -> numeri[0], 3 -> numeri[1], ..., k -> numeri[k-2], ..., n -> numeri[n-2]
72:   for(int i = 0; i <= n - 2; ++i)
73:     numeri[i] = 1;
74: 
75:   // #3.b
76:   int top = sqrt(n);
77:   for(int x = 2; x <= top; ++x)
78:   {
79:     if(!numeri[x-2]) // array contains false for that x value
80:       continue;
81: 
82:     int moltiplicando = 2;
83:     while(moltiplicando * x <= n)
84:     {
85:       numeri[moltiplicando * x - 2] = 0;
86:       ++moltiplicando;
87:     }
88:   }
89: 
90:   // #3.c
91:   return numeri;
92: 
93: }
94: 
95: