Home > Mobile >  Why is it returning 1? Generating all prime numbers in a range specified by the user in C
Why is it returning 1? Generating all prime numbers in a range specified by the user in C

Time:01-09

I have to complete the function prime in order to the function main generate all prime numbers in a range specified by the user, but when I run the code specifying 1 as minimum and 100 as maximum it returns 1 with all the prime numbers.

How can I get rid of 1, once, by definition, 1 is not a prime number?

#include <cs50.h>
#include <stdio.h>

bool prime(int number);

int main(void)
{
    int min;
    do
    {
        min = get_int("Minimum: ");
    }
    while (min < 1);

    int max;
    do
    {
        max = get_int("Maximum: ");
    }
    while (min >= max);

    for (int i = min; i <= max; i  )
    {

        if (prime(i))
        {
            printf("%i\n", i);
        }
    }
}

bool prime(int number)
{
    // TODO
    int j;
    for (j = 2; j <= number - 1; j  )
    {
        if (number % j == 0)
        {
            return false;
        }
    }
    return number;
}

Minimum: 1

Maximum: 100

1

2

3

5

7

11

13

17

19

23

29

31

37

41

43

47

53

59

61

67

71

73

79

83

89

97

CodePudding user response:

I would say that the simplest solution would be to add a test at the beginning of your prime function to indicate that any value less than "2" would yield a "false" Boolean value. With that, here is a simple refactoring of the function.

    bool prime(int number)
{
    // TODO
    if (number < 2) /* Exit gracefully if a minimum value of 1 or less is entered */
    {
        return false;
    }
    
    int j;
    for (j = 2; j <= number - 1; j  )
    {
        if (number % j == 0)
        {
            return false;
        }
    }
    return true;        /* Technically returning a value greater than zero will equate to true, but it is better to return "true" */
}

Also, note the revision of the final return statement in the function. Technically, any integer value greater than zero will be treated as a Boolean "true" value, it would be best to return the Boolean "true" value there so to be clear to anyone reading the code.

See if that meets the spirit of your project.

  • Related