通过与素数的分裂性或不划分的数字相比,将数字少于素数,并存储在数组中,如果在数组中证明是C的素数



问题

如何制作一个阵列,该数组在运行时可能会在需要时增加长度。

问题已解决

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
    int *arr;
    int count=0,i=3,j,n;
    arr=(int*)malloc(count+1*sizeof(int)); /*here i set array size to 1*/
    arr[count++]=2; /*stored 2 as array first element*/
    printf("Find all prime numbers upto :: ");
    scanf("%d",&n); /*n is the number up to which prime numbers are required*/
    here:
    {
        while(i<=n) /*start with i=3*/
        {
            j=0;
            while(arr[j]<=sqrt(i)) /*till array element value less than or equal to root of number under checking*/
            {
                if(i%arr[j]!=0) /*if remainder is not zero check*/
                    j++;        /*divisibility with next array element*/              
                else
                {
                    i++;          /*if remainder is zero then*/
                    goto here;    /*start checking for another number*/
                }
            }
            printf("%d, ",arr[count-1]); /*printing the number which was proved to be prime last time*/
            arr=(int *)realloc(arr,(count+1)*sizeof(int)); /*increasing array size by 1*/
            arr[count++]=i; /*newly proved prime is stored as next array element*/
            i++;
        }
        printf("%d, ",arr[count-1]); /*print last number proved to be prime*/
    }
}

谢谢!stackoverflow

这是我在这里的第一个问题,这个平台在解决问题,理解新概念并拥有适当的代码方面有帮助。

您的逻辑是正确的,但效率不是那么有效,而且代码也不正确。

我对您的代码进行了一些更改,现在它有效,更改如下:

scanf("%d",n) ==> scanf("%d",&n);
while (j == count) ==> while (j <= count)

现在起作用!!

相关内容

  • 没有找到相关文章

最新更新