Uva 11621 - Small Factors

// Accepted

#include<bits/stdc++.h>

#define high 2147483648
#define to_fast ios_base::sync_with_stdio(0)
#define sf scanf
#define pf printf

using namespace std;

typedef long long LL;
typedef vector<LL>vll;
typedef set<LL>sell;

vll two, three, ans;

sell s;
int anslen;

void storage(int n, int p)
{
    LL res=1;

    for(int i=1; i<=p; i++)
    {
        if(res > high)
        {
            return;
        }

        else
        {
            res *= n;
        }
    }

    s.insert(res);

    if(n == 2)
    {
        two.push_back(res);
    }

    else
    {
        three.push_back(res);
    }
}

void small_factors()
{
    for(int i=1; i<32; i++)
    {
        storage(2 , i);
        storage(3 , i);
    }

    int twolen = two.size() , threelen = three.size();

    //cout << twolen << " " << threelen;

    LL man;

    for(int i=0; i<twolen; i++)
    {
        for(int j=0; j<threelen; j++)
        {
            man = two[i] * three[j] ;

            if(man <= high)
            {
                s.insert(man);
            }
        }
    }

    sell::iterator it;
    //for(it=s.begin(); it!=s.end(); it++) cout << *it << " ";
    for(it=s.begin(); it!=s.end(); it++)
    {
        ans.push_back(*it);
    }

    //cout << ans.size();

    anslen = ans.size();
}

int search_binary(LL itm)
{
    int lo=0, hi=anslen-1,mid;

    while(lo <= hi)
    {
        mid = (lo + hi) / 2;

        if(ans[mid] == itm)
        {
            return mid;
        }

        if(ans[mid] > itm)
        {
            hi = mid-1;
        }

        if(ans[mid] < itm)
        {
            lo = mid+1;
        }
    }

    return lo;
}

int main()
{
    small_factors();
    LL num;
    while(~sf("%lld",&num) and num)
    {
        if(num == 1)
        {
            pf("1\n");
        }

        else
        {
            int index = search_binary(num);
            pf("%lld\n",ans[index]);
        }
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number