简体   繁体   English

在 C 中打印素数时输出错误

[英]wrong output while printing prime numbers in C

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

int main()
{
    int a[100]; 
    int n=0,m=1,k=0,g=0;
    for(n=0;n<100;n++) //1
    {
        a[n]=m;
        m=m+1;
    }
    int b[50]={2,3}; //2
    g=2;

    for(n=3;n<100;n++) //3
    {
        for(k=0;k<g;k++) //4
        {
            if(a[n]%b[k]==0) //5
                break;
            else if(k=g-1)  //6
            {
                b[g]=a[n];
                g=g+1;
            }
        }
    }
    printf("the prime nos are \n");
    for(m=0;m<50;m++) //7
    {
        printf("%d \n ",b[m]);
    }

    return 0;
}

In this program I have to print prime numbers between 1 to 100. The method told to follow was - to find out prime, divide a number by previous prime numbers stored in an array.在这个程序中,我必须打印 1 到 100 之间的素数。要遵循的方法是 - 找出素数,将一个数字除以存储在数组中的先前素数。 If the given number leaves 0 as remainder while dividing by any of previous primes, then it is not a prime.如果给定数字在除以任何先前的素数时留下 0 作为余数,则它不是素数。 If not, it is a prime and add that to the array.如果不是,它是一个素数并将其添加到数组中。 IN THE PROGRAM - I initialized an array of 100 numbers and stores 1 to 100 numbers in an array a (step 1).在程序中 - 我初始化了一个包含 100 个数字的数组,并将 1 到 100 个数字存储在数组 a 中(步骤 1)。 b is the array I will store primes. b是我将存储素数的数组。 I stored first two values of b in (step 2).我将b前两个值存储在(步骤 2)中。 In (step 3) I initialize array a to check for primes.在(步骤 3)中,我初始化数组a以检查素数。 In (step 4) I initialize array b to divide array a elements.在(步骤 4)中,我初始化数组b以划分数组a元素。 In (step 5) I put condition that if a number gives 0 as remainder then break out of loop and check for next number.在(步骤 5)中,我设置了条件,如果一个数字给出 0 作为余数,则跳出循环并检查下一个数字。 In (step 6) I put condition that when a number is not divisible by previous primes and check if we have divided it by the last prime no in array, if condition is true then it is prime and we increment accordingly.在(第 6 步)中,我设置了一个条件,即当一个数不能被前面的素数整除时,并检查我们是否已将它除以数组中的最后一个素数 no,如果条件为真,则它是素数,我们相应地递增。 In (step 7) I'm printing all elements of array b .在(第 7 步)中,我正在打印数组b所有元素。

The output is not coming as primes, instead it listed all odd numbers.输出不是素数,而是列出了所有奇数。 Where was I wrong and how to code it keeping logic intact.我错在哪里以及如何对其进行编码以保持逻辑完整。

Change k=g-1 to k==g-1 .k=g-1更改为k==g-1

This is because, in C, we use == to check if two expressions are equal.这是因为,在 C 中,我们使用==来检查两个表达式是否相等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM