here is my prime number generator with sieve method. calculated the primes between 2 and 100,000 in 1.75 seconds with output
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (void){
int *array;
int x,y,input;
int counter=1,element=0;
clock_t start;
clock_t end;
array=malloc(2*sizeof(int));
if(!array){
printf("Out of memory\n");
return EXIT_FAILURE;
}
array[0]=2;
array[1]='\0';
printf("Enter highest number to calculate\n>");
scanf("%d",&input);
printf("%d is prime\n",2);
start=clock();
for(x=3;x<input+1;x++){
for(y=array[0];;y=array[element]){
if(x%y==0){
element=0;
break;
}
if(element==counter-1){
array=realloc(array,1*sizeof(int));
if(!array){
printf("Out of Memory\n");
return EXIT_FAILURE;
}
array[counter]=x;
counter++;
array[counter]='\0';
printf("%d is prime\n",x);
element=0;
break;
}
element++;
}
}
end=clock();
printf("%f seconds\n",(double)(end-start)/(double)CLOCKS_PER_SEC);
free(array);
return 0;
}
p.s. Is that the right way to free a dynamic array?