EularProject 85:Counting rectangles
阿新 • • 發佈:2018-12-23
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;
}