Solving a Linear Diophantine Equation(see description for examples)

前端 未结 8 879
忘掉有多难
忘掉有多难 2020-12-16 20:27

Let me start off by clarifying that(before you guys dismiss me), this is not a homework problem and I\'m not a university student. :)

EDIT Thanks to

8条回答
  •  天涯浪人
    2020-12-16 20:42

    A brute force algorithm is as follows (3 variable case):

    int sum = 25;
    int a1 = 3;
    int a2 = 4;
    int a3 = 5;
    for (int i = 0; i * a1 <= sum; i++) {
        for (int j = 0; i * a1 + j * a2 <= sum; j++) {
            for (int k = 0; i * a1 + j * a2 + k * a3 <= sum; k++) {
                if (i * a1 + j * a2 + k * a3 == sum) {
                    System.out.println(i + "," + j + "," + k);
                }
            }
        }
    }
    

    To generalize this for the N variable case, you need to convert into a recursive form.

    This algorithm is O(f(size, a)^N) for some function f.

    • We can place bounds on f as follows: size / MaxValue(a) <= f(size, a) <= size / MinValue(a).
    • In the worst case (where all of the a[i]s are 1) f(size, a) is size.

    Either way, this is pretty horrendous for large values of N. So while the recursive N variable algorithm would be more elegant, it is probably not very practical.


    If you are willing to fork out 34 Euro's to Springer Verlag, here's a link to a paper which (according to the abstract) includes an algorithm for solving the N variable case.

提交回复
热议问题