Skip to content

Instantly share code, notes, and snippets.

@yusuketanabe
Last active March 1, 2022 04:08
Show Gist options
  • Save yusuketanabe/d073d92be2a28e926512aa8abbf61f30 to your computer and use it in GitHub Desktop.
Save yusuketanabe/d073d92be2a28e926512aa8abbf61f30 to your computer and use it in GitHub Desktop.
Recursive function memo
#include <iostream>
// a <= b
int sum_range(int a, int b) {
// Base
if (a == b) return a;
// Recursive
return a + sum_range(a+1, b);
// or return b + sum_range(a, b-1);
}
int main() {
std::cout << sum_range(1, 5) << std::endl;
std::cout << sum_range(0, 10) << std::endl;
std::cout << sum_range(5, 6) << std::endl;
}
/* output
15
55
11
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment