Monday, July 26, 2021

Power of 2 : Updated

 Here is the correct algorithm, basically it wasn't taking 1 as input properly.



#include <iostream>

#include <thread>

#include <chrono>

using namespace std;


uint64_t powerxxx(int x, int n) {

if (n <= 0) {

if (n == 0)

return 1;

else

    return 0;

}


int modval = n & 0x01;

if (modval == 1)

n--;

int count = (n >> 1);

int powertwo = x*x;

uint64_t power = 1;


while (count > 0)

{

power *= powertwo;

count--;

}


if (modval == 1)

power *= x;


return power;

}



int main()

{

auto start = std::chrono::system_clock::now();

uint64_t p = pow(3, 33);

auto end = std::chrono::system_clock::now();

std::chrono::duration<long double> diff = end - start;

std::cout << "power = " << p << ": " << diff.count() << " s\n";


start = std::chrono::system_clock::now();

p = powerxxx(3, 33);

end = std::chrono::system_clock::now();

diff = end - start;

std::cout <<"power = "<<p <<": " << diff.count() << " s\n";

return 0;

}

Power of 2 : :)

This is a new algorithm to calculate pow(x, n), where it calculates nth power of x. According to Chrono it is faster than the system pow(x,n).


#include <iostream>

#include <chrono>

using namespace std;


uint64_t powerxxx(int x, int n) {

int count  = 0;

int modval = n & 0x01;

if (modval == 1)

n = n - 1;


if (n == 0)

return 1;

else if (n < 0)

return 0;

count = (n >> 1);

int powertwo = x*x;

uint64_t power = 1;


while (count > 0)

{

power *= powertwo;

count--;

}


if (modval == 1)

power *= x;

return power;

}



int main()

{

auto start = std::chrono::system_clock::now();

uint64_t p = pow(3, 33);

auto end = std::chrono::system_clock::now();

std::chrono::duration<double> diff = end - start;

std::cout << "power = " << p << ": " << diff.count() << " s\n";


start = std::chrono::system_clock::now();

p = powerxxx(3, 33);

end = std::chrono::system_clock::now();

diff = end - start;

std::cout <<"power = "<<p <<": " << diff.count() << " s\n";


    return 0;

}