Hello everyone, the following program is supposed to allow the user to calculate all the prime numbers up into a certain maximum value, given by the user on the line of commands. After finishing said program, all that's left is to add a couple of tests, just to make sure everything works just fine, in case the user goes a little wild while trying this out.
The main upsets are the following:
1-I still haven't been able to terminate the program in the event that the given argument is a character, for instance 'a' (or any other one);
2- I also don't know how to eliminate the characters present in the string, in case the user writes a string like '2134sabb'. That is to say, i want to only take into account the numbers and discard the rest of the string.
One more thing, if there is any clear mistake i am doing, or test that needs to be added, please let me know. Thank you very much, and here's the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int
main(int argc, char **argv)
{
if( argc != 2)
{
printf("Error! Input a positive integer for the value of N!\n");
return 1;
}
int n,a,j,i,b,t;
int *v;
FILE *f1;
f1 = fopen("Prime.txt","wb");
if( f1 == NULL)
{
printf("Error! Coulnd't open file!");
return 1;
}
sscanf(argv[1],"%d",&a);
if( a < 2 )
{
printf("Error! Input a positive integer for the value of N!\n");
return 1;
}
v =(int*) malloc((a+1)*sizeof(int));
n = sqrt(a);
for(i=0;i<a+1;++i)
v[i] = 1;
i=2;
while(i<n)
{
if(v[i] != 0)
{
j = i;
b = 0;
while(i*j <= a)
{
b = i*j;
v[b] = 0;
++j;
}
}
i++;
}
printf("The prime numbers are:\n");
t=1;
for(i=2; i<a+1; ++i)
{
if(v[i] ==1 )
{
printf("%d\t",i);
if((t%6)== 0)
printf("\n");
++t;
fwrite(&i,sizeof(int),1,f1);
}
}
printf("\n");
fclose(f1);
printf("The numbers read from the file are as follows:\n");
/* Ler o ficheiro*/
f1 = fopen("Primos.txt","rb");
for(i=1;i<t;++i)
{
fread(&a,sizeof(int),1,f1);
printf("%d\n",a);
}
return 0;
}