[ create a new paste ] login | about

Link: http://codepad.org/wqLtfxsO    [ raw code | output | fork ]

outoftime - C++, pasted on Mar 16:
#include <iostream>
#include <iomanip>
#include <vector>
#include <stdint.h>

typedef int64_t LL;
LL base = 1000*1000*1000;

std::vector <int> &operator *= (std::vector <int> &a, std::vector <int> &b)
{
    std::vector <int> res(a.size() + b.size());
    for (int i = 0; i < (int)a.size(); ++i)
        for (int j = 0, carry = 0; j < (int)b.size() || carry; ++j)
        {
            LL cur = LL(a[i]) * ( j < (int)b.size() ? b[j] : 0 ) +
                carry + res[i+j];
            res[i+j] = cur % base;
            carry = cur / base;
        }
    while (res.size() && !res.back()) res.pop_back();
    a = res;
    return a;
}

std::vector <int> BinPow(int a, int n)
{
    std::vector<int> res(1, 1), b(1, a);
    while (n)
        if (n & 1) --n, res *= b;
        else n >>= 1, b *= b;
    return res;
}

std::vector <int> Pow(int a, int n)
{
    std::vector <int> res(1, 1), b(1, a);
    for(int i = 0; i < n; ++i)
        res *= b;
    return res;
}

int main()
{
    int a[] = {2,     2,     2,     2,     2,     2,     2,     2}, 
        n[] = {10000, 20000, 30000, 40000, 50000, 60000, 70000, 1000*1000};
    clock_t begin, end;
    
    for (int i = 0; i < 8; ++i)
    {
        std::cout << "Test #" << i << std::endl;
        
        begin = clock();
        std::vector <int> res = BinPow(a[i], n[i]);
        end = clock();
        
        /*std::cout << "BinPow result: " << res.back();
        std::cout.fill('0'), std::cout.width(9);
        for (int i = res.size()-2; i > -1; --i)
            std::cout << res[i];
        std::cout << std::endl << std::endl;
        std::cout.fill(' '), std::cout.width(0);*/
        std::cout << "BinPow time: " << std::setw(6) << end - begin << 
            " milisecond" << ( end - begin < 2 ? "s" : "" ) << std::endl;
            
        begin = clock();
        res = Pow(a[i], n[i]);
        end = clock();
        
        /*std::cout << "Pow result: " << res.back();
        std::cout.fill('0'), std::cout.width(9);
        for (int i = res.size()-2; i > -1; --i)
            std::cout << res[i];
        std::cout << std::endl << std::endl;
        std::cout.fill(' '), std::cout.width(0);*/
        std::cout << "Pow time:    " << std::setw(6) << end - begin <<
            " milisecond" << ( end - begin < 2 ? "s" : "" ) <<
             std::endl << std::endl;
    }
//    system("pause");
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
Test #0
BinPow time:      0 miliseconds
Pow time:     90000 milisecond

Test #1
BinPow time:      0 miliseconds
Pow time:    360000 milisecond

Test #2
BinPow time:  10000 milisecond

Timeout


Create a new paste based on this one


Comments: