Created
April 21, 2017 19:14
-
-
Save wuerges/2d167fbd0f8cf86c55f3eabfc15c57fa to your computer and use it in GitHub Desktop.
Recursive Binary Exponentiation by fast doubling.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int expbin(int a, int e, int m, int acc) { | |
if (e == 0) return acc; | |
if (e % 2 == 1) return expbin(a, e-1, m, (acc * a) % m); | |
return expbin((a * a) % m, e/2, m, acc); | |
} | |
int main() { | |
for(int i = 0; i < 10; ++i) { | |
cout << "2**"<<i<< " = " << expbin(2, i, 100000, 1) << "\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Objetivo deste exemplo é mostrar como um código recursivo pode ser transformado para se beneficiar da recursão na cauda (tail call).