I am trying to learn Dynamic Programming and one of the examples they give in Wikipedia of what is not Dynamic Programming, is a recursive way of getting Fibonacci sequence up to certain number. I.E.
Given a recursive function, say:
fib(n) = 0 if n = 0
1 if n = 1
fib(n - 1) + fib(n - 2) if n >= 2
We can easily write this recursively from its mathematic form as:
function fib(n)
if(n == 0 || n == 1)
n
else
fib(n-1) + fib(n-2)
But I cannot get the pseudo code to work.
when I do this method in Java, I get an error the operator + is undefined for methods void:
public void fib(int n) {
if (n == 0 || n == 1) {
System.out.println(n);
} else
return fib(n - 1) + fib(n - 2);
}
in the line with return fib(n - 1) + fib(n - 2), you add the return values of the fib() function. So you should actually return a (int) value, even if n==0||n==1.
public int fib(int n) {
if (n == 0 || n == 1) {
return n;
}
else {
return fib(n - 1) + fib(n - 2);
}
}
you then call and print you result from outside the function:
System.out.println(fib(42));
It has no return type so you can't mathematically add it to anything, let alone itself.
public void fib(int n) //returning void
Give it a return type
public int fib(int n) //yey \o/
Try this.
public class Test
{
public static int fib( int n )
{
if ( n == 0 || n == 1 )
return n;
else
return fib( n - 1 ) + fib( n - 2 );
}
public static void main( String[] args )
{
System.out.println(fib( 6 ));
}
}
Just change return type of fib function to int.
and in function change
if (n == 0 || n == 1){return n; }
Related
How would I go about justifying this algorithm is O(log n)?
public static long exponentiation(long x, int n){
if(n == 0){
return 1;
}
else if (n % 2 == 0){
x = exponentiation(x, n / 2);
return x * x;
}
else{
return x * exponentiation(x, n-1);
}
}
Each recursive call to method exponentiation is a multiplication step. Hence you need to count the number of recursive calls. There are several ways to achieve this. I chose to add another parameter to the method.
public static long exponentiation(long x, int n, int count) {
if (n == 0) {
System.out.println("steps = " + count);
return 1;
}
else if (n % 2 == 0) {
x = exponentiation(x, n / 2, count + 1);
return x * x;
}
else {
return x * exponentiation(x, n - 1, count + 1);
}
}
Here is the initial call to method exponentiation
exponentiation(2, 63, 0);
When I run the above code, the following is printed
steps = 11
You can use a static counter as well (without changing the prototype of the function):
public static long counter = 0;
public static long exponentiation(long x, int n){
if(n == 0){
return 1;
}
else if (n % 2 == 0){
x = exponentiation(x, n / 2);
counter++;
return x * x;
}
else{
counter++;
return x * exponentiation(x, n-1);
}
}
However, you need to reset the counter before calling the function each time, i.e., set counter = 0.
Theoretical Analysis
Note that you need to the counter to prove that it is in O(log(n)). To prove the complexity, just you need to find the complexity term by looking at the flow of the code. Suppose T(n) is the number of multiplications for computing x^n. So, based on the written code, T(n) = T(n/2) + 1, if n is even, and T(n) = T(n-1) + 1, if n is odd. Now, at least in one of two consecutive recursions, input n is even. Therefore, at most 2 log(n) is required to reach to n = 0. Because, for each even input, the next input will be halved. So, we can conclude that the algorithm is in O(log(n)).
I'm trying to solve a recursive function practice problem using Java and it has me completely stumped:
Given the small integer n (0 <= n <= 40) you need to find the n-th number of the alternating Fibonacci sequence.
The sequence starts with 0, 1, -1, 2, -3, 5, -8, 13, -21, ...
So, fib(0) = 0, fib(1) = 1 => fib(2) = -1.
I can implement the function to find the Nth fibonacci number, however the specific problem requirements are defeating me. Any time I try to implement some sort of negative number, it ends up screwing up the arithmatic instead of altering the final number that is output. My mind keeps coming back to creating some sort of conditional that only triggers on the top-most frame, but I don't think that is something that can be implemented.
Does anyone have an idea how to solve this? This is my base function without implementing any sort of the negative number requirements:
public static long fib(long n){
if (n == 0){
return 0;
} else if (n == 1){
return 1;
} else if (n == 2){
return 1;
} else {
return fib(n-2)+fib(n-1);
}
}
You can simply have another function to deal with the negative requirement:
public static int AlternatingFiboonacci(int n){
if(n > 0 && n % 2 == 0) return -fib(n); //if n is even and greater than 0
else return fib(n);
}
If you need a single working function, this should do the job
public static int fib(int n){
if(n < 2) return n;
if(n % 2 == 0) return -1 * (fib(n - 1) - fib(n - 2));
else return (-1 * fib(n - 1)) + fib(n - 2);
}
What this function does is:
when n is even, return fib(n - 1) (which is odd, thus positive) - fib(n - 2) (which is even, thus negative). The subtraction will be a positive value, that you multiply by -1.
when n is odd, return -1 * fib(n - 1) (which is even, thus negative) + fib(n - 2) (which is odd, thus positive).
Maybe it's not too late to put this as an answer:
public static long fib(long n){
if (n <= 1){
return n;
} else {
return fib(n-2) - fib(n-1);
}
}
You can first get your number:
public static long fib(long n) {
if ((n == 0) || (n == 1))
return n;
else
return fib(n - 1) + fib(n - 2);
}
And then add the minus sign if necessary:
public long result(long n){
long fib = fib(n);
if(n>0 && n%2==0) return -fib;
else return fib;
}
Just think of the formula for this one.
You want normal Fibonacci sequence but on even position they are negative. Let's say your method will be named altFib. If you apply Math.abs( altFib(n) ), you get actual value for n-th Fibonnaci number, so it's obvious that below code will also result with n-th Fibonacci number:
int fib_n = Math.abs( altFib(n-1) ) + Math.abs( altFib( n-2 ) )
Then you want it to be negative on even positions, so just use simple if else:
if( n % 2 == 0 )
return -fib_n
else
return fib_n
I am trying to make this recursive method.
public int addWithFactors(int[] a, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + (i + 1) * a[i];
}
return sum;
}
I have tried to make an if statement instead of a for loop:
if (n == 0) {...}
but I don't know what is the recursive equivalent
You can consider this code as its recursive equivalent. In your original code, you set a as a given array, and n as the maximum term, which is at most a.length - 1, and i as the current term. Your program is effectively a summation program.
The recursive helper version is shown below, and it also handles exceptional situations such as i being out of bounds:
public int addWithFactorsRecursive(int[] a, int i, int n) {
if (i < 0) // Exceptional case where
return -1;
else if (i == n - 1) // End recursion here
return (i + 1) * a[i];
else if (i < n - 1) // Return the term, and consider further terms
return (i + 1) * a[i] + addWithFactorsRecursive(a, i + 1, n);
return 0;
}
The outputs I will show to you will take an array input a, and loop addWithFactors(a, 0) to addWithFactors(a,a.length).
Here is one input I used, {1,4,9,16} and the output I got, the one on the left being your current iterative version, and the one on the right being the recursive version:
0 1 // n == 0
1 1 // n == 1
9 9 // n == 2
36 36 // n == 3
Similarly for {2,4,8,16,32,64}, I got
0 2
2 2
10 10
34 34
98 98
258 258
you can define your function like this:
public int addWithFactors(int[] a, int n) {
if (n == 1)
return a[n - 1];
return (n) * a[n - 1] + addWithFactors(a, n - 1);
}
You shuld call it like below:
addWithFactors(new int[] {1, 1, 2} ,3)
And it return 9.
private int addWithFactorsInternal(int[] a, int n, int i) {
if (i == n) {
return 0; //base case
}
return addWithFactors(a, n, i + 1) + (i + 1) * a[i];
}
addWithFactors(a, n, i + 1) makes recursive calls incrementing i. The base case is when i reaches n where you return 0.
For others, you add (i + 1) * a[i] to the recursive call and return.
If your top-level method is of the signature you've mentioned, you can call the above as
public int addWithFactors(int[] a, int n) {
return addWithFactorsInternal(a, n, 0);
}
NOTE: I didn't assume n is equal to a.length
Example:
a = {1,4 5} n = 3 (Read the LHS from top to bottom and RHS from bottom to top)
[Returns 24]
addWithFactorsInternal(a, 3, 0) - 23 + (0 + 1) * 1 = 24
addWithFactorsInternal(a, 3, 1) - 15 + (1 + 1) * 4 = 23
addWithFactorsInternal(a, 3, 2) - 0 + (2 + 1) * 5 = 15
addWithFactorsInternal(a, 3, 3) - returns 0 (base case)
I need to write a recursive method using Java called power that takes a double x and an integer n and that returns x^n. Here is what I have so far.
public static double power(double x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
else
return x * (power(x, n-1));
}
This code works as expected. However, I am trying to go the extra mile and perform the following optional exercise:
"Optional challenge: you can make this method more efficient, when n is even, using x^n = (x^(n/2))^2."
I am not sure how to implement that last formula when n is even. I do not think I can use recursion for that. I have tried to implement the following, but it also does not work because I cannot take a double to the power of an int.
if (n%2 == 0)
return (x^(n/2))^2;
Can somebody point me in the right direction? I feel like I am missing something obvious. All help appreciated.
It's exactly the same principle as for x^n == x*(x^(n-1)): Insert your recursive function for x^(n/2) and (...)^2, but make sure you don't enter an infinite recursion for n == 2 (as 2 is even, too):
if (n % 2 == 0 && n > 2)
return power(power(x, n / 2), 2);
}
Alternatively, you could just use an intermediate variable:
if (n % 2 == 0) {
double s = power(x, n / 2);
return s * s;
}
I'd probably just handle 2 as a special case, too -- and avoid the "and"-condition and extra variable:
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
if (n == 2) return x * x;
if (n % 2 == 0) return power(power(x, n / 2), 2);
return x * (power(x, n - 1));
}
P.S. I think this should work, too :)
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
if (n == 2) return x * x;
return power(x, n % 2) * power(power(x, n / 2), 2);
}
When n is even, the formula is exactly what you wrote: divide n by two, call power recursively, and square the result.
When n is odd, the formula is a little more complex: subtract 1 from n, make a recursive call for n/2, square the result, and multiply by x.
if (n%2 == 0)
return (x^(n/2))^2;
else
return x*(x^(n/2))^2;
n/2 truncates the result, so subtraction of 1 is not done explicitly. Here is an implementation in Java:
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
double pHalf = power(x, n/2);
if (n%2 == 0) {
return pHalf*pHalf;
} else {
return x*pHalf*pHalf;
}
}
Demo.
Hint: The ^ operation won't perform exponentiation in Java, but the function you wrote, power will.
Also, don't forget squaring a number is the same as just multiplying it by itself. No function call needed.
Making a small change to your function, it will reduce the number of recursive calls made:
public static double power(double x, int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
if (n % 2 == 0) {
double temp = power(x, n / 2);
return temp * temp;
} else {
return x * (power(x, n - 1));
}
}
Since
x^(2n) = (x^n)^2
you can add this rule to your method, either using the power function you wrote, as Stefan Haustein suggested, or using the regular multiplication operator, since it seems you are allowed to do that.
Note that there is no need for both the base cases n=1 and n=0, one of them suffices (prefferably use the base case n=0, since otherwise your method would not be defined for n=0).
public static double power(double x, int n) {
if (n == 0)
return 1;
else if (n % 2 == 0)
double val = power(x, n/2);
return val * val;
else
return x * (power(x, n-1));
}
There is no need to check that n>2 in any of the cases.
This just reminds me more optimisation could be done
and this following code.
class Solution:
# #param x, a float
# #param n, a integer
# #return a float
def pow(self, x, n):
if n<0:
return 1.0/self.pow(x,-n)
elif n==0:
return 1.0
elif n==1:
return x
else:
m = n & (-n)
if( m==n ):
r1 = self.pow(x,n>>1)
return r1*r1
else:
return self.pow(x,m)*self.pow(x,n-m)
what is more intermediate result could be memorised and avoid redundant computation.
Here's the working recursive power function alternative to Math.Pow class:
public class Powers {
public static long pow(long x, long p) {
if (p == 0) {
return 1;
}
if (p % 2 == 0) {
long a = pow(x, (p / 2));
return a * a; //This line
} else {
long a = pow(x, ((p - 1) / 2));
return x * a * a; //This line
}
}
}
If I try to be clever and use as much recursion as possible by changing the lines mentioned above to return pow(a, 2) and return x * pow(a, 2), I get a stack overflow error. I get that it should cause considerably more calls to pow, but I don't think it should loop like it appears to. Can anyone explain me through this? Thanks
Doing this you will get the following sequence of calls:
pow(a, 2) -> pow(a, 1) -> pow(a, 0) -> pow(1, 2) -> pow(1, 1) -> pow(1, 0) -> pow(1, 2) -> ...
You should either debug this with some IDE, or simply add some expression in the beginning of the method:
public static long pow(long x, long p) {
System.out.println ("x = " + x + ", p = " + p);
...
Then, read the output, it will contain the sequence of calls of pow