-
Notifications
You must be signed in to change notification settings - Fork 363
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
Changes from 1 commit
860bd1d
546bc5b
348ad07
60b4356
e0d5338
98fd22b
f61dcfd
ea182d5
7bee107
e90a43e
c4255a0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/* | ||
<Fast Power> | ||
-------------- | ||
Fast Power is an optimized algorithm to compute exponentiation in a short time. | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
||
*/ | ||
#include <iostream> | ||
|
||
using namespace std; | ||
typedef long long ll; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use |
||
|
||
//Function that returns x raised to the power of y | ||
ll fastPower (ll x,ll y) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please use more meaningful variable names like |
||
{ | ||
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add a trailing |
||
return 0; | ||
} |
There was a problem hiding this comment.
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).