JKac
JKac

Reputation: 76

Problems with printing output C

So I have to write a code for school. I did, but my outputs are not the way they asked for. This code gives me prime number between 2 different numbers. So i have to print those numbers in rows. But yeah there are getting zeros between the answers below you can see what I mean. How can I fix this?

#include <stdio.h>

int is_prime (int number)
{
    int is_prime= 1, i;

    if (number < 2)
    {
        is_prime = 0;
    }
    else
    {
        for(i = 2; (i * i) <= number; i++)
        {
            if ((number % i) == 0)
            {
                is_prime = 0;
                break;
            }
            else
            {
                is_prime = 1;
            }
        }
    }
    return is_prime;
}

int main (void)
{
    int lower_limit, upper_limit, i;

    scanf("%d\n%d", &lower_limit, &upper_limit);

    for(i = lower_limit; i <= upper_limit; i++)
    {
        if (is_prime (i))
        {
            printf("\n%d", i);
        }
        else
        {
            printf("\n%d", is_prime(i));
        }
    }

    return 0;
}

Output

0
11
0
13
0
0
0
17
0
19
0

Reference

11
13
17
19

Upvotes: 0

Views: 87

Answers (3)

chux
chux

Reputation: 153447

Another problem: overflow.

Avoid int overflow in i*i, which is undeifned behavior (UB). This can happen when number is a prime near INT_MAX.

 // for(i = 2; (i * i) <= number; i++)
 for(i = 2; i <= number/i; i++)

A good compiler will see the nearby number%i and number/i and emit efficient code for the two of them, thus not incurring an expensive 2nd operation.


The below also overflows when upper_limit == INT_MAX

for(i = lower_limit; i <= upper_limit; i++)

Perhaps

for(i = lower_limit; i - 1 < upper_limit; i++)

OK as long as lower_limit > INT_MIN.

Upvotes: 2

0___________
0___________

Reputation: 67476

If the number is prime number just print it. No else needed - even worse it is incorrect.

You can simplyfy the the is_prime function

int is_prime (int number)
{
    int is_prime = number > 1, i;

    for(i = 2; (i * i) <= number; i++)
    {
        if ((number % i) == 0)
        {
            is_prime = 0;
            break;
        }
    }
    return is_prime;
}


int main (void)
{
    int lower_limit, upper_limit, i;

    scanf("%d\n%d", &lower_limit, &upper_limit);

    for(i = lower_limit; i <= upper_limit; i++)
    {
        if (is_prime (i))
        {
            printf("\n%d", i);
        }

    }
    return 0;
}

https://godbolt.org/z/4d8qhx

Upvotes: 2

dbush
dbush

Reputation: 223747

It's in this if block:

    if (is_prime (i))
    {
        printf("\n%d", i);
    }
    else
    {
        printf("\n%d", is_prime(i));
    }

What this says is "if the number is prime print it, otherwise print whether it is prime (which at this point you've established it's not)".

Just get rid of the else block.

Upvotes: 5

Related Questions