Can someone please tell me why my programme is outputting all primes up to inputted n
and also just the number n+2
(whether it is prime or not)? And also sometimes n+1
if it is prime, e.g. for inputting n=10
, output is 2,3,5,7,11,12
.
Here is my code:
/*Write a program that reads in a number n between 1 and 100,000 and then lists all the prime numbers between 1 and n inclusive.*/
#include
#define LIMIT 100000 /*size of integers array*/
#define PRIMES 100000 /*size of primes array*/
int main(){
int i,j,numbers[LIMIT];
int primes[PRIMES];
int n, count;
count = 0;
/*Read in an upper limit, n*/
printf("Please enter a value for n: ");
if (scanf("%d", &n) !=1) {
printf("Sorry, cannot read n.\n");
return 1;
}
/*fill the array with natural numbers*/
for (i=0;i<=n;i++){
numbers[i]=i+2;
}
/*sieve the non-primes*/
for (i=0;i<=n;i++){
if (numbers[i]!=-1){
for (j=2*numbers[i]-2;j<n;j+=numbers[i])
numbers[j]=-1;
}
}
/*transfer the primes to their own array*/
j = 0;
for (i=0;i<=n&&j<PRIMES;i++)
if (numbers[i]!=-1) {
primes[j++] = numbers[i];
count = count + 1; }
/*print*/
for (i=0;i<count;i++)
printf("%d\n",primes[i]);
return 0;
}