I have been given the task to write an algorithm given this simple expression:
f (0) = 0, f (1) = 1, f (2n) = f (n), f (2n + 1) = f (n) + f (n + 1).
The restrictions are: Time Complexity O(logn), Space Complexity O(1). I wrote this basic recursion function:
int func (int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
if (n % 2 == 0) {
return func(n / 2);
} else {
return func(n / 2) + func((n / 2) + 1);
}
}
There is probably something smarter using an iterative algorithm because I need O(1) space complexity (I think my code is not O(1) space because of the recursive calls).