Determine whether the combination of two legged animals and 4 legged animals are present

128 Views Asked by At

there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct. if correct print yes or print no if a combination of these animals are not present

for example

Sample input

3 8

where 3 is the number of animals present in the garden and 8 are the total legs

sample output

Yes

sample input

2 100

sample output

No

so i found a solution to this which does work but i would like to understand the mathematics behind this if some one could explain;

    int n, x;
    cin >> n >> x;
    for(int i = 0; i <= n; i++)
    {
        if(i * 2 + (n - i) * 4 == x)
        {
         cout  << "Yes";
         return 0;
        }
    }
    cout << "No";

     return 0; 
} 

it is this part of the code i dont understand the math part of it

i * 2 + (n - i) * 4 == x
1

There are 1 best solutions below

0
On BEST ANSWER

The line you ask about is just checking whether there can be $i$ cranes. If there are $i$ cranes, there are $n-i$ monkeys, since there are $n$ animals altogether, and the number of legs is $2i+4(n-i)$. The code simply checks if this equals $x$.

This is a lot of unnecessary work though. If $$2i+4(n-i)=x$$ then $$\begin{align}2i+4n-4i=x\\2i=4n-x\\i=2n-\frac x2\tag1 \end{align}$$ Since this must be an integer, $x$ must be even. Furthermore, we must have $$0\leq2n-\frac x2\leq n,$$ since the number of cranes can't be negative, and it can't be more the the number of animals. That is, we must have $x$ is even, and $$2n\leq x\leq4n.$$ If these conditions are satisfied, the number of cranes is given by $(1)$.