Long condition C++ [closed]

I do not know whether this solution is more efficient, but maybe it is more readable and easier to code:

#include <iostream>
#include <cstdlib>

int main()
{
    const int magicNumber = 32640;
    const int maxOffset = 1920;

    int n;
    std::cin >> n;

    int y = 20;

    const std::div_t divresult = std::div(n, magicNumber);

    if (divresult.rem > 0 && divresult.rem < maxOffset &&       // (#1)
            divresult.quot >= 1 && divresult.quot <= 10)    {   // (#2)
        y = 40;
    }

    std::cout << "y: " << y << std::endl;

    return 0;
}

EDIT:

Here, I make use of the fact that for your condition to be true, your variable to test (n) has to be between multiples of 32640 or magicNumber and multiples of that number plus some offset (maxOffset). This is the remainder of dividing your variable by the magicNumber, cf. (#1).

But this is not valid for every integer, but only for certain multiples, as expressed by the || in your original solution. In my solution, this is expressed by the quotient, cf. (#2).

While programming this answer, I learned that there is a function std::div that computes these two in one step and returns them in a structure of type std::div_t, so you can use the two members in the condition. Here you can find more information on this function.

Leave a Comment