In: Computer Science
Please use java language Thanks!
Implement a recursive method called "pow" that takes 2 integers, x and y, as parameters and returns the value xy (x raised to the power y). The exponent must be non-negative. If a negative argument is given for the exponent, then an exception should be thrown.
Implement a recursive method called "fib" that takes a positive integer, n, as a parameter and returns the nth Fibonacci value. Assume that the first 2 values in the Fibonacci sequence are 1 and 1. So, fib(1) should return 1, fib(2) should return 1, fib(3) should return 2, fib(4) should return 3, and so on. The return type should be double. Note that Fibonacci numbers are integers, but they get very large very quickly. So we will use double as our return type only because that will allow very large values to be returned. If a non-positive value is passed as an argument, then an exception should be thrown.
NOTE: You would never implement Fibonacci recursively in real life.
Implement a method called "add" that takes an array of doubles as a parameter and returns the sum of all the values in the array. You must use recursion in your solution. (You will probably want to implement private "helper" method that is recursive. Your public "add" method won't actually be recursive, but it will call the recursive helper method.)
package math;
public class PowerAndFib {
public static double power(int x,int y) throws Exception{
if(y<0) //if y <0 throw exception
throw new Exception("Exponent can not be negative");
if(y==0)
return 1;
return x*power(x,y-1); //if Exponent is positive
}
public static double fib(int n) throws Exception{
if(n<0)
throw new Exception("Exponent can not be negative");
if(n==1 || n==2)
return 1;
return fib(n-1)+fib(n-2); //return sum of prev two element
}
public static double Add(double ar[]){
return Add(ar,0);
}
public static double Add(double ar[],int i){ //takes arrray and index as paramter
if(i<ar.length){ //i is less than length
return ar[i]+Add(ar,i+1); //add sum to next recursive call
}
return 0; //else return 0
}
public static void main(String[] args) throws Exception {
System.out.println(power(4,2));
System.out.println(fib(4));
double ar[]={2,4,5,6,8};
System.out.println(Add(ar));
}
}
output
16.0
3.0
25.0