Skip to content

Instantly share code, notes, and snippets.

@wuerges
Created April 21, 2017 19:14
Show Gist options
  • Save wuerges/2d167fbd0f8cf86c55f3eabfc15c57fa to your computer and use it in GitHub Desktop.
Save wuerges/2d167fbd0f8cf86c55f3eabfc15c57fa to your computer and use it in GitHub Desktop.
Recursive Binary Exponentiation by fast doubling.
#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;
}
@wuerges
Copy link
Author

wuerges commented Apr 21, 2017

Objetivo deste exemplo é mostrar como um código recursivo pode ser transformado para se beneficiar da recursão na cauda (tail call).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment