Paweł
Paweł

Reputation: 1

What is the problem with this boolean function?

I was wondering what I may have done wrong in writing this simple function which is supposed to return true if the given number is a prime, or false if not a prime.

bool isPrime(int num)
{
    if (num <= 1)
    {
        status = false;
    }
    else
    {
        for (int i = 1; i <= num; i++)
        {
            if (num % i == 0)
            {
                dividers++;
            }
        }
        if (dividers == 2)
        {
            status = true;
        }
        else 
        {
            status = false;
        }
    }
    return status;
}

Obviously, my main looks like this:

bool isPrime(int num);
bool status;
int dividers = 0;

int main() {

    isPrime(2);
    if (!isPrime)
    {
        std::cout << "Not prime" << std::endl;
    }
    else
    {
        std::cout << "Prime" << std::endl;
    }

    return 0;
}

I'm a C++ beginner and I'd really appreciate it if someone could help me there and correct my logic. Have a good day:)

Upvotes: 0

Views: 89

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

The immediate problem is in this two lines:

isPrime(2);
if (!isPrime)

The first line calls the function and discards the returned value. The second line converts a pointer to the function to bool. The output of your code does not depend on what you actually do in isPrime.

That is not how you call a function and use its result!

Instead you want

if (isPrime(2)) { 

or

bool isP = isPrime(2);
if (isP) { ...

As mentioned in comments, there are also problems in the implementation of isPrime, but I hope this is enough to set you back on the right track.

PS: You should get rid of the global variable status. You do not need both, the return value and a global that stores the result, and if you can choose, you should definitely go for the return value.

Upvotes: 4

Related Questions