标签:
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个不同大小的长方形,如下图所示:
尽管没有一个长方形网格中包含有恰好两百万个长方形,但有许多长方形网格中包含的长方形数目接近两百万,求其中最接近这一数目的长方形网格的面积
解题
有下面内容:
对于任意矩形M*N
其中1*1的矩阵有M*N个
1*2的矩阵有M*(N-1)个
2*1的矩阵有(M-1)*N个
实际上只要确定小矩阵左上角顶点在大矩形中的位置,这个矩阵的位置就唯一确定了
所有在任意矩形M*N中,矩阵i*j有(M-i+1)*(N-j+1)个
所以对于M*N的矩阵总的矩阵数量是:
int num = 0; for(int i =1;i<= m;i++){ for(int j =1;j<= n;j++){ num += (m-i + 1)*(n - j+1); } }
更让人想不到是是直接计算矩阵的数量:
num = (m+1)*m*(n+1)*n/4
Java
package Level3; import java.util.Random; public class PE085{ static void run() { int limit = 100; int close = Integer.MAX_VALUE; int area = 0; for(int m =1;m< limit ;m++){ for(int n = 1;n< limit ;n++){ int num = grid_num(m,n); if (num>2000000) break; if( Math.abs(num - 2000000 ) < Math.abs(close - 2000000)){ close = num; area = n*m; } } } System.out.println(area); } public static int grid_num2(int m , int n){ int num = 0; num = (m+1)*m*(n+1)*n/4; return num; } // 2772 // running time=0s0ms public static int grid_num(int m , int n){ int num = 0; for(int i =1;i<= m;i++){ for(int j =1;j<= n;j++){ num += (m-i + 1)*(n - j+1); } } return num; } // 2772 // running time=0s20ms public static void main(String[] args){ long t0 = System.currentTimeMillis(); run(); long t1 = System.currentTimeMillis(); long t = t1 - t0; System.out.println("running time="+t/1000+"s"+t%1000+"ms"); } }
你说是不是很流氓,这个规律,我怎么那么聪慧的会发现?
Project Euler 85 :Counting rectangles 数长方形
标签:
原文地址:http://www.cnblogs.com/theskulls/p/4998875.html