Question

y=20;
x=32640;
b=1920;
if (
    n > (x*1) && n < ((x*1)+(b))||
    n > (x*2) && n < ((x*2)+(b))||
    n > (x*3) && n < ((x*3)+(b))||
    n > (x*4) && n < ((x*4)+(b))||
    n > (x*5) && n < ((x*5)+(b))||
    n > (x*6) && n < ((x*6)+(b))||
    n > (x*7) && n < ((x*7)+(b))||
    n > (x*8) && n < ((x*8)+(b))||
    n > (x*9) && n < ((x*9)+(b))||
    n > (x*10) && n < ((x*10)+(b))
    ){y = 40;}

In C++ is there a quicker way to do this as I only increment the number after 32640 for each condition?

(quicker in performance)

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top