project-euler/085_counting_rectangles.c

44 lines
923 B
C
Raw Normal View History

2023-03-26 22:59:33 +02:00
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int dev(int a, int b, int p);
int calcb(int a, int p);
int main(int argc, char *argv[])
{
int p = 2000000;
int a, b;
int d1, d2; //dev of b, dev of b+1
int cd, td; //current dev, min dev
int tb, ta; //best a and b
ta = tb = td = -1;
for(a = 1; (b = calcb(a, p)) + 1 >= a; ++a){
d1 = dev(a, b, p);
d2 = dev(a, b + 1, p);
cd = d1 > d2 ? d2 : d1;
b += (d2 == cd);
if(cd < td || td == -1){
//smaller deviation
td = cd;
tb = b;
ta = a;
}
}
//printf("a = %d\nb = %d\ndev = %d\narea = %d\n", ta, tb, td, ta*tb);
printf("%d\n", ta*tb);
}
//calculate b
int calcb(int a, int p)
{
return (sqrt(1 + ((float) 16*p)/(a*a + a)) - 1)/2;
}
//eval deviation
int dev(int a, int b, int p)
{
return abs(a*b*(a + 1)*(b + 1)/4 - p);
}