Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Fast Power in Number Theory #76

Merged
merged 11 commits into from
Jul 20, 2017
47 changes: 47 additions & 0 deletions NumberTheory/FastPower.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
<Fast Power>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove the angle brackets (< and >) and indent the block by one level (4 spaces).

--------------
Fast Power is an optimized algorithm to compute exponentiation in a short time.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be helpful for others if you could also mention in 1 or 2 lines more what the algorithm does.


Time Complexity
-----------------
O(log(N)) where N is the power the number is raised to.

Space Complexity
------------------
O(log(N)) where N is the power the number is raised to.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where N is the power the number is raised to
More simply, where N is the exponent.


*/
#include <iostream>

using namespace std;
typedef long long ll;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use unsigned long long for double the range.


//Function that returns x raised to the power of y
ll fastPower (ll x,ll y)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use more meaningful variable names like base and exponent instead of just x and y.
Also, rename the function to fast_power to adhere to the guidelines.

{
if (y==0) return 1;

if (y%2==1)
{
return fastPower(x,y-1) * x;
}
else
{
x = fastPower(x,y/2);
return (x*x);
}
}

//Testing the function
int main()
{
int base,power;
cout<<"Enter the number and the power it's raised to:"<<endl;

cin>>base>>power;

cout<<fastPower(base,power);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a trailing "\n" so that the prompt on terminals is displayed in the next line.

return 0;
}