1

I'm pretty much done with my code which calculates all primes between 2 and 1000. However, I need make a code which scans my prime array and prints whether its a prime or not.

For those who dont understand what I want: After calculating all primes between 2 and 1000, I want the user to give a random number which then tells the user whether its a prime or not. With this code below, it doesnt work for some reason... can someone tell me what I did wrong?

#include <stdio.h>
#include <stdbool.h>




int main () {


int durch [1000] = {0};

for (int i = 2; i <= 1000; i++)
{
    if (!durch[i-2])
    {
        for (int j = 2*i; j <= 1000; j+= i)
        {
            durch[j-2] = 1;


        }

    }
}

int primzahlen [1000];
int anzahl = 0;
int n;

for (int i = 2; i <= 1000; i++)
{
    if (!durch [i-2])
    {
        primzahlen[anzahl] = i;
        anzahl++;

// printf ("%i : %i\n", anzahl, i);
scanf ("%i\n", &n);

if (n = primzahlen[anzahl]){
    printf ("Yes it is a prime!\n");
    break;
}
else {
    printf ("No it isnt a prime!\n");
    break;
}

    }
}


    return 0;
}

I really cant figure that part out.. I feel like I miss something? Can somebody help me out please?

Kise948
  • 67
  • 4
  • 2
    the posted code contains a logic error: Regarding: `if (n = primzahlen[anzahl]){` This is an assignment, but you actually want a comparison. Suggest: `if (n == primzahlen[anzahl]){`. Also, the index `anzahl` contains the index to the highest entry in the array: `primzahlen[]` which (probably) is not the entry of interest for the user supplied value. – user3629249 Nov 20 '19 at 22:19
  • 1
    OT: the posted code contains some 'magic' numbers. 'magic' numbers are numbers with no basis. I.E. 1000. Suggest using an `enum` statement or a `#define` statement to give that 'magic' number a meaningful name, then using that meaningful name throughout the code – user3629249 Nov 20 '19 at 22:24

2 Answers2

2

you are discarding value of n variable here:

if (n = primzahlen[anzahl]){

you probably intended to compare numbers instead of assignment

if (n == primzahlen[anzahl]){
Maxim Sagaydachny
  • 2,098
  • 3
  • 11
  • 22
2

The whole second part of your program isn't necessary. You can just simplify it to:

#include <stdio.h>
#include <stdbool.h>

int main () {
    int i;
    int durch [1000] = {0};
    int n;

    for (i = 2; i <= 1000; i++)
    {
        if (!durch[i-2])
        {
            for (int j = 2*i; j <= 1000; j+= i)
            {
                durch[j-2] = 1;
            }
        }
    }

    scanf ("%i", &n);

    if ((n > 1) && !durch [n-2]) {
        printf ("Yes it is a prime!\n");
    }
    else {
        printf ("No it isnt a prime!\n");
    }

    return 0;
}

And note scanf ("%i\n", &n); will ask for 2 numbers. You need to use scanf ("%i", &n);

See: scanf() curious behaviour!

hko
  • 548
  • 2
  • 19