Created
October 10, 2017 10:52
-
-
Save jordi-petit/97d8fc010182b8da6d671a0ad2fccc5f to your computer and use it in GitHub Desktop.
AP1 2017-10-10 Recursivitat 1
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
// Funció recursiva que retorna el factorial d'un natural. | |
// Prec: n>=0. | |
int factorial(int n) { | |
if (n == 0) return 1; | |
else return n * factorial(n - 1); | |
} |
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
// Acció recursiva que escriu el nombre n en base b (del dret). | |
// Prec: n>=0, 2<=b<=10. | |
void escriu(int n, int b) { | |
if (n < b) { | |
cout << n; | |
} else { | |
escriu(n/b, b); | |
cout << n%b; | |
} | |
} | |
// Millora (no vista a classe) | |
void escriu(int n, int b) { | |
if (n >= b) escriu(n/b, b); | |
cout << n%b; | |
} | |
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
// Funció recursiva que calcula el màxim comú divisor de dos naturals | |
int mcd(int a, int b) { | |
if (a == 0) return b; | |
return mcd(b%a, a); | |
} | |
// O també: | |
int mcd(int a, int b) { | |
return a == 0 ? b : mcd(b%a, a); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment