C Programming: Using Relational Operators - Less than vs less than equals

430 views Asked by At

I'm working on a textbook problem and I wrote this piece of code below to identify all prime numbers below a user inputted positive number:

#include <stdio.h>

int main(void)
{
    int j, input, notaprime;

    scanf_s("%d", &input);

    printf("List of prime numbers:\n");
    for (; input >= 2; input--)
    {
        notaprime = 0;
        for (j = 2; j < input; j++) //OR (for(j = 2; j*j <= input; j++)
        {
            if ((input % j) == 0)
            {
                notaprime = 1;
                break;
            }
            else
            {
                ;
            }
        }

        if (notaprime)
        {
            ;
        }
        else
        {
            printf("%d\n", input);
        }
    }

    return 0;
}

When 30 is entered as input, the following is the output:

30
List of prime numbers:
29
23
19
17
13
11
7
5
3
2
Press any key to continue . . .

However, when I change the relational operator in the inner for loop from:

        for (j = 2; j < input; j++)

to:

        for (j = 2; j <= input; j++) //Changed from less than to less than equals

The following becomes the output of input value 30:

30
List of prime numbers:
Press any key to continue . . .

Now, prime numbers are no longer printing, but I can't think of any logical reason why this is so. My brain hurts now from thinking of possible reasons why this should be valid. Please help. Thanks!

I tried this on codeblocks 16.01 and Visual Studio Community 2015. Output is the same.

1

There are 1 answers

1
Shashi Kundan On BEST ANSWER

There is Logical Error in your code

We know that a prime number is a number which is divided by 1 or itself

when you do for (j = 2; j < input; j++) then you check all number below than input which is correct.

But when you do for (j = 2; j <= input; j++) you check upto input.

Since every number is divided by itself (input % j) == 0 every time, notaprime = 1; statment is true hence no output is produced