Created
June 11, 2025 19:07
-
-
Save thinkphp/40a2474e00b4fa64cae42b6750b2d7c4 to your computer and use it in GitHub Desktop.
divide et impera factorial
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 <stdio.h> | |
//varianta iterativa | |
int fact(int n) { | |
int p = 1; | |
for(int i = 1; i <= n; ++i) { | |
p *= i; | |
} | |
return p; | |
} | |
//1,2,3,4,5 | |
//1*2*3*4*5 | |
//[1,2,3] [4,5] | |
//[1,2],[3] [4][5] | |
void factorial_divide_et_impera(int lo, int hi, int *res) { | |
int a, b; | |
if(lo == hi) { | |
*res = lo; | |
} else { | |
int m = (lo + hi) / 2; | |
factorial_divide_et_impera(lo, m, &a); | |
factorial_divide_et_impera(m + 1, hi, &b); | |
*res = a * b; | |
} | |
} | |
int main(int argc, char const *argv[]) { | |
int n = 5; | |
//5! = 1 * 2 * 3 * 4 * 5 | |
int res; | |
printf("5! = %d (varianta iterative clasica)\n", fact(n)); | |
factorial_divide_et_impera(1, n, &res); | |
printf("5! = %d (divide et impera)", res); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment