bool is_prime(int a)
{
     if(a==1){return false;}
     if(a<4){return true;}
     if(a%2==0){return false;}
     if(a<9){return true;}
     if(a%3==0){return false;}
     int i;
     for(i=5;(i*i)<=a;i+=6)
     {
                           if(a%i==0){return false;}
                           if(a%(i+2)==0){return false;}
     }
     return true;
}

critique welcome.

Edited 5 Years Ago by frogboy77: n/a

You could simplify 3-7: if(a || a<4 || !(a&1) || a<9 || !(a%3)) return(false);

Edited 5 Years Ago by MosaicFuneral: n/a

ok but i find following one statement after another easier than trying to evaluate 3 or 4 in one go. thanks for comments and i will keep them in mind.

/***********************************************************
if a valid prime number return true or false
***********************************************************/
int is_prime(int _iVal)
{
    char bPrime;
    bPrime = true;
    for (int ii(2); ii < _iVal / 2; ii++)
    {
        if (!(_iVal % ii)){
            bPrime = false;
            break;
        }
    }
    return bPrime;
}

Would be better

bPrime is a bool not a char.

The return being a false or truth also means that it should be bool is_prime(...) not int is_prime(...)

Edited 5 Years Ago by MosaicFuneral: n/a

so you're returning a char value from an int function with a bool value?

Edited 5 Years Ago by frogboy77: n/a

/***********************************************************
Check to see if a valid prime number
***********************************************************/
bool is_prime(int _iVal)
{
    bool bPrime;
    bPrime = true;
    for (int ii(2); ii < _iVal / 2; ii++)
    {
        if (!(_iVal % ii)){
            bPrime = false;
            break;
        }
    }

    return bPrime;
}

Should be thus & returns 1 or 0
Point taken I didn't write the function got off the forum sometime ago. Did not spot that nice one.

maybe just me being a noob but that looks like shit!

Edited 5 Years Ago by frogboy77: n/a

maybe just me being a noob but that looks like shit!

How so? It's very straightforward in fashion.

It could use a little cleaning up, but it looks fine for the most part.

Edited 5 Years Ago by MosaicFuneral: n/a

still waiting for a clarification on this

You can also remove a<4 because you already have a<9.

This article has been dead for over six months. Start a new discussion instead.