Numbers II
Binary Search
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
ll findTerm(ll a, ll b, ll lcm, ll value)
{
return (value / a) + (value / b) - (value / lcm);
}
ll solve(ll a, ll b, ll n)
{
ll gcd = __gcd(a,b);
ll lcm = (a * b) / gcd;
ll rema = lcm / a;
ll remb = lcm / b;
ll low = (n / (rema + remb - 1)) * lcm;
ll high = min(a, b) * n;
ll ans;
while(low <= high)
{
ll mid = (low + high) / 2;
ll term = findTerm(a, b, lcm, mid);
if(term >= n)
{
ans = mid;
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return ans;
}
int main()
{
int t;
ll a, b, n;
cin >> t;
while(t--)
{
cin >> a >> b >> n;
cout << solve(a, b, n) << endl;
}
return 0;
}
Comments
Post a Comment