We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<iostream>#include<cmath>intmain(){unsignedinttests=1;std::cin>>tests;while(tests--){unsignedinttarget=2000000;std::cin>>target;// assume x <= y, therefore x <= sqrt(limit)unsignedintroot=sqrt(target);unsignedintbestRectangles=0;unsignedintbestArea=0;for(unsignedintx=1;x<=root+1;x++)// allow slight overshooting{// start with a sqaureunsignedinty=x;// number of rectanglesunsignedintrectangles=0;// slowly increase y until too many rectangle in the griddo{unsignedintarea=x*y;// the formula derived aboverectangles=x*(x+1)*y*(y+1)/4;// closer to desired number of rectangles than before ?if(abs(bestRectangles-target)>abs(rectangles-target)){bestRectangles=rectangles;bestArea=area;}// prefer larger areas, too (additional requirement of Hackerrank)if(abs(bestRectangles-target)==abs(rectangles-target)&&bestArea<area)bestArea=area;y++;}while(rectangles<target);// just a speed-up ... abortion when the inner loop exited with a square area x*y// => it means that no further solutions possible, area already too largeif(y==x+1)// plus one because y was incremented before leaving the inner loopbreak;}std::cout<<bestArea<<std::endl;}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #85: Counting rectangles
You are viewing a single comment's thread. Return to all comments →
100 Points C++