Skip to content

Commit

Permalink
Add fast power algorithm with tests
Browse files Browse the repository at this point in the history
closes #75
  • Loading branch information
ahmad307 authored and faheel committed Jul 20, 2017
1 parent 0bead6c commit 97d92b3
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
72 changes: 72 additions & 0 deletions NumberTheory/FastPower.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
Fast Power
----------------
Fast Power is an optimized algorithm to compute exponentiation in a short time.
It calculates the power by squaring, meaning we divide the power by 2 on each step and multiply
the base by itself. We keep doing this until the power is 0 where we return 1.
Time Complexity
-----------------
O(log(N)) where N is the exponent.
Space Complexity
-----------------
O(log(N)) where N is the exponent.
*/
#include <iostream>
#include <cmath>

using namespace std;
typedef unsigned long long ull;

//Function that returns base raised to the exponent
ull fast_power (ull base,ull exponent,ull mod = ULLONG_MAX)
{
if (exponent==0) return 1;

if (exponent%2==1) //If the power is odd
{
return (fast_power(base,exponent-1,mod) * base)%mod;
}
else //If the power is even
{
base = fast_power(base,exponent/2,mod);
return (base*base)%mod;
}
}

#ifndef FAST_POWER_TEST

int main()
{
//Testing the function
ull base,exponent;
cout<<"Enter the number and its exponent:"<<endl;

cin>>base>>exponent;

if (base == 0 && exponent == 0)
{
cout<<"undefined"<<endl;
}
else
{
int digits_required = floor(exponent * log10(base)) + 1;

if (digits_required > 19)
{
cout<<endl<<fast_power(base,exponent,1000000007)<<endl;
cout<<"*The output is modulo 10^9+7"<<endl;
}
else
{
cout<<endl<<fast_power(base,exponent)<<endl;
}
}

return 0;
}

#endif
28 changes: 28 additions & 0 deletions Test/NumberTheory/FastPower.test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#define FAST_POWER_TEST
#define CATCH_CONFIG_MAIN

#include "../catch.hpp"
#include "../../NumberTheory/FastPower.cpp"


TEST_CASE("Base cases", "[fast_power]") {
//REQUIRE(fast_power(0,0) == undefined);
REQUIRE(fast_power(0,1) == 0);
REQUIRE(fast_power(1,0) == 1);
REQUIRE(fast_power(1,1) == 1);
}

TEST_CASE("Normal cases", "[fast_power]") {
REQUIRE(fast_power(2,2) == 4);
REQUIRE(fast_power(2,4) == 16);
REQUIRE(fast_power(3,4) == 81);
REQUIRE(fast_power(7,9) == 40353607);
REQUIRE(fast_power(15,10) == 576650390625);
}

TEST_CASE("Overflow cases", "[fast_power]") {
REQUIRE(fast_power(2,100,1000000007) == 976371285);
REQUIRE(fast_power(10,99,1000000007) == 22673271);
}

#undef FAST_POWER_TEST

0 comments on commit 97d92b3

Please sign in to comment.