Saturday, 21 July 2012

UVa 516 - Prime Land Solution

#include<iostream>
#include<list>
#include<string>
#include<cstring>
#include<sstream>
#include<cctype>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<stack>
#include<fstream>
#include<cstdlib>
#include<vector>
#include<map>
#include<set>
#include<utility>
#include<iomanip>
#include<queue>

using namespace std;

#define INF (1<<29)
#define SET(a) memset(a,-1,sizeof(a))
#define ALL(a) a.begin(),a.end()
#define CLR(a) memset(a,0,sizeof(a))
#define FILL(a,v) memset(a,v,sizeof(a))
#define PB push_back
#define FOR(i,n) for(int i = 0;i<n;i++)
#define PI acos(-1.0)
#define EPS 1e-9
#define MP(a,b) make_pair(a,b)
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define LL long long
#define MX 100000
#define MOD 1000000007

bool stats[33000+10];
vector<LL>prime;
LL N,n,primeSize,cnt;
map<LL, LL>factor;
map<LL, LL>freq;

void PrimeGenerate()
{
    LL i,j,sqrtN;

    for(i=4;i<=33000;i+=2)
        stats[i]=true;

    sqrtN=sqrt(33000);

    for(i=3;i<=sqrtN;i+=2)
    {
        if(!stats[i])
            for(j=i*i;j<=33000;j+=i+i)
                stats[j]=true;
    }

    for(i=2;i<=33000;i++)
        if(!stats[i])
            prime.PB(i);

    primeSize=prime.size();
}


void PrimeFactorize()
{
    LL i;
    cnt=0;

    for(i=0;i<primeSize;i++)
    {
        if(n%prime[i]==0)
        {
            factor[cnt]=prime[i];
            cnt++;

            while(n%prime[i]==0)
                {
                    freq[cnt-1]++;
                    n/=prime[i];
                }
        }

        if(n==1)    break;
    }
}


int main()
{
   LL multy,base,exp;
   string line;
   PrimeGenerate();
   while(getline(cin,line))
   {
       if(line=="0") break;
       multy=1;
       istringstream ss(line);
       while(ss>>base)
       {
           ss>>exp;
           multy*=pow(base,exp);
       }
       n=multy-1;
       N=n;
       factor.clear();
       freq.clear();
       PrimeFactorize();
       for(LL i=cnt-1;i>0;i--)
            cout<<factor[i]<<" "<<freq[i]<<" ";
        cout<<factor[0]<<" "<<freq[0]<<endl;
   }
return 0;
}

No comments:

Post a Comment