通过小于它的质数的整除性检查一个数是否为质数,如果在 C 中证明是质数,则将其存储在数组中

Check a number as prime or not by divisibility with prime numbers less than it and storing that in an array if proved to be prime in 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*/
    }
}

谢谢!堆栈溢出

这是我在 C 语言中的第一个问题,这个平台在解决问题、理解新概念和编写正确代码方面帮助了我很多。

你的逻辑是对的,但是效率不高,代码也不对。

我对你的代码做了一些修改,现在可以使用了,修改如下:

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

现在可以使用了!!