My approach :-
-
x and y is the length of the rectange so we need length and breadth closer to x and y respectively.
-
Initialy let len1=-1, len2=-1, br1=-1, br2=-1 . Then we will get len1 = c * (x/c),
len2 = c * (x/c+1) , br1 = c * (y/c), br2 = c * (y/c +1). -
if any of the len or br gets equal to 0 than we will discard it from further calculation . target = x * y .
-
finally we will find (val1 * br1) , (val1 * br2), (val2 * br1) and (val2 * br2). Select the one which is closest to the target.
My Code :-
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll compare(ll a,ll b,ll tar,ll ans)
{
if(a!=-1&&b!=-1)
{
ll val = a*b;
ll curr=abs(val-tar);
ll old=abs(ans-tar);
//cout<<"curr and old are "<<curr<<" "<<old<<endl;
//cout<<curr<<" "<<old<<endl;
ans = (curr<old)? val:ans;
}
//cout<<ans<<endl;
return ans ;
}
int main()
{
//write your code here
int t ; cin>>t;
for(int i=0;i<t;i++)
{
ll x,y,c; cin>>x>>y>>c;
ll val1=-1,val2=-1,val3=-1,val4=-1;
if(x%c==0)
{
val1=x;
}
else
{
ll z=x/c;
val1=z*c; z++; val2=z*c;
if(val1==0)
val1=-1;
}
if(y%c==0)
{
val3=y;
}
else
{
ll z=y/c;
val3=z*c; z++; val4=z*c;
if(val3==0)
val3=-1;
}
ll ans = LLONG_MAX ;
ll tar=x*y;
/* cout<<"val1, val2 , val3 , val4 , tar, ans "
<<val1<<" "<<val2<<" "<<val3<<" "<<val4<<" "
<<tar<<" "<<ans<<" "<<endl; */
ans = compare(val1,val3,tar,ans);
ans = compare(val1,val4,tar,ans);
ans = compare(val2,val3,tar,ans);
ans = compare(val2,val4,tar,ans);
cout<<ans<<endl;
}
return 0;
}