美文网首页
Taxicab numbers

Taxicab numbers

作者: 一叶夏幕 | 来源:发表于2019-03-09 15:37 被阅读0次
    A taxicab number is an integer that can be expressed as the sum of two cubes of integers in two different ways: a^3+b^3=c^3+d^3.
    For example, 1729=9^3+10^3=1^3+12^3. Design an algorithm to find all taxicab numbers with a, b, c, and d less than N.
    Version 1: Use time proportional to N^2logN and space proportional to N^2.
    Version 2: Use time proportional to N^2logN and space proportional to N
    
    
    
        class Taxicab implements Comparable<Taxicab>{
            int n1;
            int n2;
            int cube;
    
            Taxicab(int n1, int n2) {
                this.n1 = n1;
                this.n2 = n2;
                this.cube = n1 * n1 * n1 + n2 * n2 * n2;
            }
    
            @Override
            public int compareTo(Taxicab that) {
                if (that.cube > this.cube) return -1;
                if (that.cube < this.cube) return 1;
                return 0;
            }
    
            @Override
            public boolean equals(Object o) {
                if (o instanceof Taxicab) {
                    if (((Taxicab)o).compareTo(this) == 0)
                    return true;
                }
                return false;
            }
    
            @Override
            public String toString() {
                return "number: " + cube + " (" + n1 + ", " + n2 + ")";
            }
        }
    
        public void findTaxinumber(int N) {
            MinPQ<Taxicab> candidates = new MinPQ<Taxicab>();
    
            for (int i = 1; i <= N; i++) {
                for (int j = i + 1; j <= N; j++) {
                    Taxicab t = new Taxicab(i, j);
                    if (candidates.size() < N) {
                        candidates.insert(t);
                    }
                    else {
                        Queue<Taxicab> temp = new Queue<Taxicab>();
                        Taxicab min = candidates.delMin();
                        while (candidates.min().equals(min)) {
                            temp.enqueue(candidates.delMin());
                        }
                        if (!t.equals(min)) {
                            candidates.insert(t);
                        }
                        else {
                            temp.enqueue(t);
                        }
                        if (!temp.isEmpty()) {
                            for (Taxicab taxi: temp) {
                                System.out.println(taxi);
                            }
                            System.out.println(min);
                        }
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            PriorityQueue p = new PriorityQueue();
            p.findTaxinumber(12);
        }

    相关文章

      网友评论

          本文标题:Taxicab numbers

          本文链接:https://www.haomeiwen.com/subject/mznspqtx.html