Last active
September 6, 2016 20:54
-
-
Save dgodfrey206/7fee49348378dd98837dcced5690dad0 to your computer and use it in GitHub Desktop.
Write a recursive function that takes an integer n as a parameter and returns the following sum/subtraction of odd numbers 1 - 3 + 5 - 7 + 9....+/- n (if n is even, the last term is 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
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
// 1 - 3 + 5 - 7 + 9 ... +/- n | |
// recursive | |
int f1(int n) { | |
if (n == 1) return 1; | |
if (n % 2 == 0) n--; | |
if ((n + 1) % 4 == 0) return f1(n-2) - n; | |
/* else */ return f1(n-2) + n; | |
} | |
// iterative (dynamic programming) | |
int f2(int n) { | |
int R[n+1]; | |
R[1] = R[2] = 1; | |
for (int i = 3; i <= n; ++i) { | |
int k = i; | |
if (k % 2 == 0) k--; | |
if ((k + 1) % 4 == 0) R[i] = R[k-2] - k; | |
else R[i] = R[k-2] + k; | |
} | |
return R[n]; | |
} | |
int main(){ | |
for (int i = 1; i <= 10; ++i) | |
std::cout << f2(2*i-1) << " "; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment