2.4.25
Posted w-j-c
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.4.25相关的知识,希望对你有一定的参考价值。
question:
Computational number theory. Write a program CubeSum.java that prints out all integers of the form a^3 + b^3 where a and b are integers between 0 and N in sorted order, without using excessive space. That is, instead od computing an array of the N^2 sums and sorting them, build a minimum-oriented priority queue is nonempty, remove the smallest item(i^3 + j^3, i, j), print it, and then, if j < N, insert the item (i^3 + (j+1)^3), i, j+1). Use this program to find all distinct integers a, b, c, and d between 0 and 10^6 such that a^3 + b^3 = c^3 + d^3.
answer:
import edu.princeton.cs.algs4.*; public class CubeSum implements Comparable<CubeSum> { private int sum; private int x; private int y; public CubeSum(int i, int j) { sum = i*i*i + j*j*j; x = i; y = j; } public int compareTo(CubeSum t) { return this.sum - t.sum; } public void show() { StdOut.println(sum + " " + x + " " + y); } public static void main(String[] args) { int N = StdIn.readInt(); MinPQ<CubeSum> cubesum = new MinPQ<CubeSum>(); for(int i = 0; i <= N; i++) cubesum.insert(new CubeSum(i,0)); while(cubesum.size() > 1) { CubeSum t = cubesum.delMin(); CubeSum c = cubesum.min(); if(t.sum == c.sum) StdOut.println(t.x + "^3 " + "+" + t.y + "^3 = " + c.x + "^3 " + "+" + c.y + "^3 = " + t.sum); if(t.y < N) { cubesum.insert(new CubeSum(t.x,t.y+1)); } } } }
以上是关于2.4.25的主要内容,如果未能解决你的问题,请参考以下文章