Cod sursa(job #1182971)

Utilizator abel1090Abel Putovits abel1090 Data 8 mai 2014 08:51:20
Problema Ridicare la putere in timp logaritmic Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
///LGPUT
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

unsigned long power(unsigned n, unsigned p) {
    stack<pair<unsigned, unsigned> > s;
    s.push(make_pair(n, p));
    unsigned long result;

    pair<unsigned, unsigned> current;
    while(!s.empty()) {
        current = s.top();
        s.pop();

        if(current.second == 0) result = 1;
        else
            if(current.second == 1) result = current.first;
            else
                if(current.second % 2 == 0) s.push(make_pair(current.first*current.first, current.second/2));
                else
                    s.push(make_pair(current.first*current.first, (current.second-1)/2));
    }

    return result;
}

int main() {
    ifstream fin("lgput.in");
    ofstream fout("lgput.out");

    unsigned N, P;

    fin >> N >> P;

    fout << power(N, P);
    fout << '\n';

    return 0;
}