javascriptmathlinear-algebra

JavaScript - Is there an efficient way to check if an integer "k" is a linear combination of the values in an array of prime numbers?


I have an arbitrarily large integer k and an array of arbitrarily many positive prime numbers [p_1, p_2, ..., p_n]. Using JavaScript, I want to check if k can be expressed as a linear combination of the values of the array with nonnegative integer coefficients.

However, I haven't been able to figure out a method for determining if any given k is a linear combination of the values in any given array.

The only answer to a similar question on this site doesn't work because all the values in my arrays are prime numbers: their GCD is always 1, the remainder is always 0, and the return value of that answer's expression is always True, even when it should be False.

As an example, if the array has the values [5, 7, 13], then k = 12 is a valid linear combination (1×5 + 1×7 + 0×13) while k = 16 is not.

Additionally, the code in the linked question and answer only checks for multiples less than or equal to the array values, and I want to be able to check numbers much bigger than that.

Is what I want possible to achieve?


Solution

  • You could take a recursive approach by taking a delta of actual value or check with the next value.

    const
        check = (values, k) => {
            const
                iter = (rest, index) => {
                    if (!rest) return true;
                    if (rest < 0 || index >= values.length) return false;
                    return iter(rest - values[index], index)
                        || iter(rest, index + 1);
                };
        
            return iter(k, 0);
        };
    
    console.log(check([5, 7, 13], 12));
    console.log(check([5, 7, 13], 16));