Solving a Linear Diophantine Equation(see description for examples)

前端 未结 8 948
忘掉有多难
忘掉有多难 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 21:06

    I happened to write Java code for this. Please help yourself. The solutions are not extensively tested, but it seems to work well so far.

    package expt.qp;
    
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class LinearDiophantine {
    
        private Map sol = new LinkedHashMap();
        private Map coeff = new HashMap();
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // Fill up the data
            // 3x + 4y + 5z + 3a = 25
            LinearDiophantine ld = new LinearDiophantine();
            ld.coeff.put(1, 1);ld.coeff.put(2, 2);ld.coeff.put(3, 3);ld.coeff.put(4, 4);
            Map coeffCopy = new HashMap(ld.coeff);
            int total=30;
    
            // Real algo begins here
            ld.findPossibleSolutions(total, coeffCopy);
    
        }
    
        private void findPossibleSolutions(int total, Map coeff) {
            int index=returnLargestIndex(coeff);
            int range = (int) Math.floor(total/coeff.get(index));
            if(range*coeff.get(index) == total) {
                sol.put(index, range);
                displaySolution();
                //System.out.println();
                range--;
            }
            if(coeff.size() == 1) {
                return;
            }
            while(range>=0) {
                int remTotal = total - range*coeff.get(index);
                Map coeffCopy = new HashMap(coeff);
                coeffCopy.remove(index);
                sol.put(index, range);
                findPossibleSolutions(remTotal, coeffCopy);
                range--;
            }
        }
    
        private void displaySolution() {
            int total = 0;
            for(int i : sol.keySet()) {
                //System.out.print(coeff.get(i)+"("+sol.get(i)+"), ");
                total = total + (coeff.get(i)*sol.get(i));
            }
            if(total != 30)
                System.out.print(total+",");
        }
    
        /**
         * @param coeff
         */
        private int returnLargestIndex(Map coeff) {
            int largestKey = coeff.keySet().iterator().next();
            for(int i : coeff.keySet()) {
                if(coeff.get(i)>coeff.get(largestKey)) {
                    largestKey=i;
                }
            }
            return largestKey;
        }
    
    }
    

提交回复
热议问题