EularProject 85:Counting rectangles

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangzhengyi03539/article/details/78447084

Andrew Zhang
Nov 4, 2017

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.

Answer:
2772
Completed on Sat, 4 Nov 2017, 23:21

solution code:

#include <iostream>
using namespace std;

#define TAR 2000000

int func(int x, int y)
{
    return x*(x + 1)*y*(y + 1) / 4;
}

int main()
{
    int i = 1, j = 1;
    int count = func(i, j);
    int x = 1, y = 1, val = TAR;
    while (count < TAR) {
        j++;
        count = func(i, j);
        if (abs(count - TAR) < val) {
            x = i;
            y = j;
            val = abs(count - TAR);
        }
    }
    while (i < j) {
        i++;
        count = func(i, j);
        if (count > TAR) {
            while (true) {
                if (abs(count - TAR) < val) {
                    x = i;
                    y = j;
                    val = abs(count - TAR);
                }
                if (count < TAR) {
                    break;
                }
                j--;
                count = func(i, j);
            };
        } else {
            while (true) {
                if (abs(count - TAR) < val) {
                    x = i;
                    y = j;
                    val = abs(count - TAR);
                }
                if (count > TAR) {
                    break;
                }
                j++;
                count = func(i, j);
            };
        }
    }

    cout << "result" << endl;
    cout << "x = " << x << ", y = " << y << ", val = " << val << endl;
    cout << "area = " << x*y << endl;
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhangzhengyi03539/article/details/78447084