Last active
October 27, 2020 19:24
-
-
Save Rex-Ferrer/84fb42a2d54a65469b888f7b982a5fb2 to your computer and use it in GitHub Desktop.
Advanced Algorithms: Russian Peasant Product
This file contains 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
int getRussianPeasantProduct(int n, int m, int extra){ | |
int next_n; | |
int next_m; | |
int next_extra; | |
if (n == 1){ | |
return m + extra; | |
} else if (n % 2 == 0) { | |
next_n = n / 2 as int; | |
next_m = m * 2; | |
return getRussianPeasantProduct(next_n, next_m, extra); | |
} else { | |
next_n = ((n - 1) / 2) as int; | |
next_m = m * 2; | |
next_extra = extra + m; | |
return getRussianPeasantProduct(next_n, next_m, next_extra); | |
} | |
} | |
void main(){ | |
print(getRussianPeasantProduct(50, 65, 0)); | |
assert(getRussianPeasantProduct(50, 65, 0) == 50 * 65); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://dartpad.dev/84fb42a2d54a65469b888f7b982a5fb2