I'm writing a code for the "Sieve of Eratosthenes" in C, which prints all the prime numbers up to n. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include "input2.h"
int main()
{
int n = read_int();
int length = n-1;
int *block_of_memory = (int *)malloc(sizeof(int));
for(int i = 2; i <= length; i++)
{
block_of_memory[i] = 1;
}
for(int i = 2; i*i <= length; i++)
{
if(block_of_memory[i] == 1)
{
for(int j = i*i; j < length; j = j+i)
{
block_of_memory[j] = 0;
}
}
}
for (int i = 1; i <= length; ++i)
{
if(block_of_memory[i] == 1)
{
printf("%d\n", i);
}
}
print_prime(block_of_memory, length);
free(block_of_memory);
return 0;
}
I'm not sure what I'm doing wrong here. When I want all the prime uptown 5 (for example), I get:
Give a number: 5
1
1
4, 5,