-3

I am not able to find prime numbers of 8 digits in spite of increasing size of array a. It is working for smaller numbers:

#include<stdio.h>
#include<math.h>

int main()
{
    int n,a[100000],i,m,k;
    scanf("%d",&n);
    for (i=2;i<=n;i++)
        a[i]=1;
    m=(sqrt(n)+1);
    for (i=2;i<=m;i++)
        if (a[i]==1)
            for (k=i*i;k<=n;k+=i)
                a[k]=0;
    for (i=0;i<=n;i++)
        if (a[i]==1)
            printf("%d\t",i);
    return 0;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 3
    If you increase the size of `a` so that it's large enough to have 8 digit indices then you will most likely get a stack overflow. – Paul R Feb 14 '15 at 09:55

1 Answers1

4

I could not get larger than 6 digits either by using the locally declared array. Such an array uses stack memory, which is in short supply compared to heap memory. The other problem is that you didn't check if the value entered for n will break the fixed size array that you declared. I solved both problems by using malloc() to allocate the exact amount of memory required, from the heap, and checked to see if the memory allocation worked.

The other small thing I tidied up was the use of \t to format the output. Once the numbers get large that will look messy. I gave a field width of 10 because that will contain an 8-digit number, also because most text terminals have a width of 80, so the numbers won't break across lines.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    int n,i,m,k;
    int *a;
    scanf("%d",&n);
    if ((a = malloc((n+1)*sizeof(int))) == NULL) {
        printf ("Not enough memory\n");
        exit (1);
    }
    for (i=2;i<=n;i++)
        a[i]=1;
    m=(sqrt(n)+1);
    for (i=2;i<=m;i++)
        if (a[i]==1)
            for (k=i*i;k<=n;k+=i)
                a[k]=0;
    for (i=0;i<=n;i++)
        if (a[i]==1)
            printf("%10d",i);
    printf("\n");
    free (a);
    return 0;
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56