project euler 85

来源:互联网 发布:sql编程基础 编辑:程序博客网 时间:2024/06/17 14:35

Problem 85


Counting rectangles

By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles:

Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution.


数长方形

如果数得足够仔细,能看出在一个3乘2的长方形网格中包含有18个不同大小的长方形,如下图所示:

尽管没有一个长方形网格中包含有恰好两百万个长方形,但有许多长方形网格中包含的长方形数目接近两百万,求其中最接近这一数目的长方形网格的面积。

package projecteuler;import junit.framework.TestCase;public class Prj85 extends TestCase {public static final int LIMIT = 2000000;/** * 1, 2, 3 , ....m; * 2, 4, 6 , ... 2m; * ....................;  * n, 2n,3n,...,nm; */public void testCountingRectangles() {int min = Integer.MAX_VALUE;int iID = 0;int jID = 0;for (int i = 1; i < 100; i++) {for (int j = 1; j < 100; j++) {int val = Math.abs(calculateRetangles(i, j) - LIMIT);if (val < min) {min = val;iID = i;jID = j;}}}String fstr = "area=%d,min=%d,(m,n)=(%d,%d)";fstr = String.format(fstr, iID * jID, calculateRetangles(iID, jID),iID, jID);System.out.println(fstr);}int calculateRetangles(int m, int n) {int _m = Math.abs(m);int _n = Math.abs(n);return (1 + _m) * _m / 2 * (1 + _n) * _n / 2;}}


0 0