{-1,0,1} kind of linear combination

54 Views Asked by At

I really don't know how to express this idea with a clearer title.

Here's the question:

A merchant dropped a stone of 40 pounds onto the ground and broke into 4 parts. And the 4 little stones can be used to weigh any pound in range [0,40].

To express it in mathematic language:

$$a+b+c+d = 40$$ $$\forall n \in [0,40], n = \lambda_1a+\lambda_2b+\lambda_3c+\lambda_4d, \lambda_i \in (-1,0,1)$$

We want to find a solution for $a,b,c,d$. Using computer to iterate all possible solutions, I got the answer that is 27,9,3,1. However, I am wondering if there's a more elegant mathematic solution?

There are the code:

#include <iostream>
bool test(int n, int a, int b, int c, int d)
{
    if (-1 * a + -1 * b + -1 * c + -1 * d == n)
    {
        return true;
    }
    \\... there are just "linear combinations". 
    if (1 * a + 1 * b + 1 * c + 1 * d == n)
    {
        return true;
    }
    return false;
}

bool test_all(int a,int b,int c,int d)
{
    for(int i=1;i<=40;i++)
    {
        if(!test(i,a,b,c,d))
        {
            return false;
        }
    }
    return true;

}

int main()
{
    for (int a = 0; a < 40; a++)
    {
        for (int b = 0; b < 40; b++)
        {
            for (int c = 0; c < 40; c++)
            {
                for (int d = 0; d < 40; d++)
                {
                    if(test_all(a,b,c,d))
                    {
                        std::cout << a <<std::endl<< b <<std::endl<< c<<std::endl << d<<std::endl;
                        return 0;
                    }
                }
            }
        }
    }
}
```
1

There are 1 best solutions below

1
On

The key is to realise that the kind of linear combination you want is exactly the kind number systems are good at realising, and that $\{-1, 0, 1\}$ is a set with $3$ elements that is as good as $\{0, 1, 2\}$ as "digits", except that the numbers they make it possible to write are symmetric around $0$, and with 4 ternary digits you can write $81$ ($3^4$ - $0, 1,\ldots, 80$) different numbers, placed symmetrically around $0$, that is the integers from $-40$ to $40$.