Uva 10334 - Ray Through Glasses

//Verdict :: Accepted
//Time :: 0.003

#include<bits/stdc++.h>
using namespace std;

string ans[1009];

string BuiltIn(string a, string b)
{
    int i=a.size()-1, j=b.size()-1, res=0,carry=0;
    string s="";

    if(i > j)
    {
        for(; i>=0 ; i--)
        {
            res = a[i] - 48;

            if(j>=0)
            {
                res+=(b[j]-48);
                j--;
            }

            res+=carry;

            if(res > 10)
            {
                s+=((res%10)+48);
                carry=res/10;
            }
            else
            {
                s+=((res%10)+48);
                carry=res/10;
            }
        }

        if(carry)
        {
            s+=(carry+48);
        }
    }

    else
    {
        for(; i>=0 and j>=0; i--,j--)
        {
            res=(a[i]-48) + (b[j]-48);
            res+=carry;

            if(res > 10)
            {
                s+=((res%10)+48);
                carry=res/10;
            }
            else
            {
                s+=((res%10)+48);
                carry=res/10;
            }
        }

        if(carry)
        {
            s+=(carry+48);
        }
    }

    reverse(s.begin(),s.end());
    //cout << s;

    return s;
}

string BigInt(string x, string y)
{
    if(x.size() < y.size())
    {
        swap(x,y);
    }

    if(x.size() > y.size())
    {
        return BuiltIn(x,y);
    }
    else
    {
        return BuiltIn(x,y);
    }
}

void precalculate()
{
    ans[0] = "1";
    ans[1] = "2";

    for(int i=2; i<=1005; i++)
    {
        ans[i] = BigInt(ans[i-2],ans[i-1]);
        //cout << ans[i] << " ";
    }
}

int main()
{
    precalculate();
    int n;
    while(cin >> n)
    {
        cout << ans[n] << "\n";
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number