How to check if an integer is linear combination of elements in an array?

删除回忆录丶 提交于 2019-12-22 01:12:23

问题


How to check if an integer can be expressed as linear combination of elements in a given array of length n? Currently I can code for the specific case when n=2, but I don't know how to code when n is unknown.

This is the function when n=2 (when there are only two elements in the array):

bool check(int array[], int n, int value){//n values in the array //    

  for (int i=1; i<array[0]; i++){
     for (int j=1; j<array[1]; j++){
        if ((i*array[0]+j*array[1])%value==0){
            printf("x=%d, y=%d, i=%d, j=%d\n", array[0], array[1], i, j);
            return 1;
        }
    }
    }
return 0;
}

回答1:


I remember from my first-year discrete math courses that n is a linear combination of x and y if and only if n is a multiple of the gcd(x,y) (i.e. if value % gcd(x,y) == 0)

you can use this notion as a powerful asset in your code.

The moral here is to calculate the gcd between all the elements in your set and keep checking if value is divisible by the gcd(x,y). If it is, then return 1, else 0.

I'll leave the implementation of the gcd() function to you (there are many examples of it online), but here is how you can incorporate it in your existing code:

bool check(int array[], int n, int value){
    for (int i = 0; i < n - 1; i++) {            // notice we only iterate up to n - 1
        for (int j = i + 1; j < n; j++) {
            if (value % gcd(array[i], array[j]) == 0) {
               printf("x=%d, y=%d, i=%d, j=%d\n", array[0], array[1], i, j);
               return 1;
            }
        }  
    }
    return 0;
}


来源:https://stackoverflow.com/questions/47583925/how-to-check-if-an-integer-is-linear-combination-of-elements-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!