Search code examples
javamathrecursionfibonaccifactorial

Java Fibonacci /Math Involvement/No Packages


I've been having trouble with this problem where:

I have to write a recursive method that solves a multiplication problem of any two integers, whether positive or negative.

before this I wrote a method that is a part of a sequence and another method that did the same thing as my problem but it is only for positive numbers:

I'm stuck at Fib3,

where I am supposed to multiply -7 by 8 but,

since B is greater than 0,

it automatically inputs A which is just -7 (result should be -56)

Here is my Code:

public class P4_Icel_Murad_Fibonacci
{
   private int N;
   private int result;
   private int A; 
   private int B;
   private int result2;
   private int result3;
    P4_Icel_Murad_Fibonacci(){
  }
   int Fib1(int N){
     if (N == 1 || N == 0){
        return N;
        }else if (N >= 1){
            result = Fib1(N-1) + Fib1(N-2);
            result = Fib1(N-1) + Fib1(N-2);
            result = Fib1(N-1) + Fib1(N-2);
            result = Fib1(N-1) + Fib1(N-2);
        }
     return result;
  }
  int Fib2(int A, int B){
      if ( A == 1 || B == 1){
          return A;
        }else if ( A >= 0 && B >= 0){
          result2 =  (A + 2) * Fib2(A-3,B);
        }
        return result2;
    }
  int Fib3(int A, int B){
      if ( A >= 0 || B >= 0){
          return A;
        }else if ( A < 0 || B < 0){
          result3 =  (A) * Fib3(A-3,B);
        }
        return result3;
    }
}

Driver:

public class Driver
{   
    public static void main(String[] args){
        P4_Icel_Murad_Fibonacci create = new P4_Icel_Murad_Fibonacci();
        System.out.println("Fib(11) = " + create.Fib1(11));
        System.out.println("7 * 8 = " + create.Fib2(7,8));
        System.out.println("-7 * 8 = " + create.Fib3(-7,8));
    } 
}

Solution

  • I am not sure whether the OP has correctly described the problem.

    I would do something like:

    int multiply(int a, int b) {
        if(b==0){
            return 0;
        } else if (b > 0){
            return a + multiply(a, b-1)
        } else { // b < 0; 
            return -a + multiply(a, b+1)
        }
    }
    

    That is recursive, handles both positive and negative numbers. Its not very efficient really, you might like to insure that abs(b) is less than abs(a) so you might add a line like:

    if( abs(a) < abs (b)){
       return multiply(b,a)
    }
    

    first thing to at least insure that it doesn't do a million iterations for 0 * 1,000,000.

    Obviously this is a terrible way to do multiplication but it seems to answer the OP's problem as described.