pages:
  • 1
Ln (x) dx SAYS

H!i. this is my solution. but i ate a big time.:D why there is a faster solution? and what's that?

#include<iostream>
#include<cmath>
using namespace std;

long long gcd_func(long long a, long long b)
{   
    if(b == 0)
        return a;
    else
        return gcd_func(b, a % b);          
}

void get_xy(long long m, long long n, long long gcd, 
               long long &x, long long &y)
{   
    if(m < n)
    {
        x = m / gcd;
        y = n / gcd;
    }   
    else
    {       
        x = n / gcd;
        y = m / gcd;            
    }   
}

void get_xy_2(long long m, long long n,
               long long &x, long long &y)
{
    if(m < n)
    {
        x = m;
        y = n;
    }
    else
    {
        x = n;
        y = m;
    }
}

int main()
{
    long long t, m, n, x, y, gcd, k, l, i, j;
    double a, b, c, t1, t2, t3, ans;
    cin >> t;
    while(t--)
    {
        ans = 0;
        cin >> m >> n;      

        if(m == n)
            cout << sqrt(2.0) * m << endl;
        else
        {
            //gcd = gcd_func(m, n);
            //get_xy(m, n, gcd, x, y);
            get_xy_2(m, n, x, y);
            if(x % 2 == 0 || y % 2 == 0)
                //cout << gcd * sqrt((double)(x*x + y*y)) / 2 << endl;
                cout << sqrt((double)(x*x + y*y)) / 2 << endl;
            else
            {
                a = 1;
                b = (double)x / y;
                k = y / x;
                c = a - k*b;
                l = (y - x) / 2 + 1;                
                if(k % 2)
                    j = 1;
                else
                    j = 0;
                for(i = 1; i < x; i++, j++)                 
                {
                    t1 = c * (double)y / x;
                    t2 = 1 - t1;
                    t3 = t2 * (double)x / y;

                    if(j%2 == 0)
                        ans += sqrt(c*c + t1*t1);
                    else
                        ans += sqrt(t2*t2 + t3*t3);

                    a = 1 - t3;                 
                    k = a / b;
                    c = a - k*b;
                }               
                ans += (l * sqrt(b * b + 1));
                //cout << ans * gcd << endl;
                cout << ans << endl;
                //cout << "yohahahaha!\n";
            }               
        }
    }
}
AMiR SAYS

There is a faster approach for this problem.

The gcd is a clever trick and essential, but that's not enough! There is a more straightforward solution.