kira
kira

Reputation: 286

Data type of an intermediate variable

I am writing a program (in cpp) to check the primality of a given number

The point where i am struck is , I need to check in between the program wether the value i obtained upon some arithmetic operations on the input is an integer or not

i.e lets say input is 'a'

I want to know how to check if 'b' is integer or not (FYI, b=(a+1)/6 )

My attempt for this :

int main()
{
    using std::cin;
    using std::cout;
    int b,c;
    int a;
    cout<<"enter the number";
    cin>>a;
    b=(a+1)/6;
    c=(a-1)/6;
    if (b is an integer)
        cout << "The given number is  prime";
    else if (c is an integer)
        cin << "The given number is  prime!";
    else
        cout<<"The number is not prime";                  
    return 0;
}

Upvotes: 1

Views: 472

Answers (3)

Paul R
Paul R

Reputation: 213059

Using the modulus operator % as suggested in other answers is probably the best solution, but to answer your question more literally, you can tell whether the result of an integer division is exact like this:

b=(a+1)/6;
c=(a-1)/6;
if (b * 6 == a + 1) // if b is an integer
    cout << "The given number is  prime";
else if (c * 6 == a - 1) // if c is an integer
    cin << "The given number is  prime!";
else
    cout<<"The number is not prime";

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 792477

As a and 1 both have type int, so does a+1 and (a+1). As 6 also has type int, (a+1)/6 will also have type int whatever the value of a.

What I think you really want to know is whether 6 evenly divides (a+1). For this you can use the modulus operator. 6 evenly divides (a+1) if and only if (a+1)%6 == 0.

Upvotes: 1

Alexander Pavlov
Alexander Pavlov

Reputation: 32296

You should use if (((a+1)%6) == 0) (see the modulus operator).

Upvotes: 5

Related Questions