1

We was told to make a binary search with the class Recursion. However I'm stuck as the recursion isn't working properly according to my professor(Didn't elaborate when I asked for help) and been working with a fellow student. We come to the conclusion of needing int count but I'm not sure where or how to implement it. Java isn't my strongest language so a guide or hint would be very helpful.

            public class Recursive {
            public int BinarySearch(int x[], int target, int low, int high)
            {
               if (low >= high) return -1; 
               int mid = (low + high)/2;
               if (x[mid] > target)
                  return BinarySearch(x, target, low, mid-1); 
               else if (x[mid] < target)
                  return BinarySearch(x, target, mid+1, high); ;
               return mid;
            }
            public int firstNnumber(int n)
            {
               if (n < 1) return 0;
               return firstNnumber(n-1) + n;
            }
            public int firstNnumber2(int n)
            {
               if (n==1) return 1;
               if (n==2) return 3;
               boolean even = (n%2 == 0);
               n /= 2;
               if (even)
               {
                   return 2*firstNnumber2(n) + n*n;
               }
               else
                   return 2*firstNnumber2(n) + (n + 1)*(1+n);
            }
            public int gaussian(int n)
            {
               return  n*(n+1)/2;
            }

            static public void main(String [] args)
            {
               Recursive r = new Recursive();
               System.out.println("By Gussain, Sum of first 100000 integers=" + r.gaussian(10000));
               System.out.println("By recurssion 2,    Sum of first 100000 integers=" + r.firstNnumber2(6)); 
            }


            }       

This is what is printed, I don't understand what's the problem with my code.

By Gussain, Sum of first 100000 integers=50005000 By recurssion 2, Sum of first 100000 integers=21

1 Answer 1

1

your are calling with the wrong params, try calling with

static public void main(String [] args){
  Recursive r = new Recursive();
  System.out.println("By Gussain, Sum of first 100000 integers=" + r.gaussian(10000));
  System.out.println("By recurssion 2,    Sum of first 100000 integers=" + r.firstNnumber2(10000)); 
}

Sign up to request clarification or add additional context in comments.

1 Comment

This will fix the output. repl.it/repls/PureFlakyTransversals tested and both outputs are the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.