oriolmarti97

[X87649] Recursive powers of 2

Apr 30th, 2017
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.46 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. /*
  5.  * Cost logarítmic, menys intuitiva, però més ràpida
  6.  */
  7. int two_to_n(int n) {
  8.     if (n==0) return 1;
  9.     int aux=two_to_n(n/2);
  10.     if (n%2==0) return aux*aux;
  11.     return 2*aux*aux;
  12. }
  13. /*
  14.  * Cost lineal, més senzilla de pensar, però més costosa a la llarga
  15.  */
  16. int two_to_n(int n) {
  17.     if (n==0) return 1;
  18.     return 2*two_to_n(n-1);
  19. }
  20.  
  21. int main() {
  22.     int n;
  23.     while (cin >>n) cout <<two_to_n(n)<<endl;
  24. }
  25.  
  26. //By Patata
Advertisement
Add Comment
Please, Sign In to add comment