diff --git a/NumberTheory/FastPower.cpp b/NumberTheory/FastPower.cpp new file mode 100644 index 00000000..ca7b5e73 --- /dev/null +++ b/NumberTheory/FastPower.cpp @@ -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 +#include + +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:"<>base>>exponent; + + if (base == 0 && exponent == 0) + { + cout<<"undefined"< 19) + { + cout<