public class Fibonacci2 {
static int fib(int n) {
if(n==1 || n==2) {
return(1);
}
return fib((n-1)+fib(n-2));
}
// Stackoverflow error //
public static void main(String[] args) {
int i, n = 7;
for(i=1; i<=n; i++)
System.out.println("FIbonaci series" + fib(i));
}
}
This program suffer from runtime exception (stackoverflow) please tell how to deal with it.
You step through the code in your debugger and you will see that
return fib((n-1)+fib(n-2));
should be
return fib(n-1) + fib(n-2);
as what you have is like
return fib(fib(n-2));
which quickly creates very high levels of recursion.
replace fib((n-1)+fib(n-2)) with fib(n-1)+fib(n-2).
May be it will help you
public static void fib(int initial, int current, int n) {
int sum = 0;
sum = initial + current;
if (initial == 0) {
System.out.print(current + " ");
}
System.out.print(sum + " ");
initial = current;
current = sum;
if (n > 2) {
fib(initial, current, n - 1);
}
}
Related
I'm new to binary searches and I tried a program that would find the position of a value inputted by a user. My code however only seems to return a low=-1 value which leads to the program saying "the value was not found". I think I did something wrong with my binary search code, but I am not experienced with these and may have missed something? Here's my code for the binary search:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length;
int low = -1;
int middle = (high+low)/2;
while(high-low>1)
{
count++;
middle = (high+low)/2;
if(numbers[middle]>target)
{
high = middle;
}
else if(numbers[middle]<target)
{
low = middle;
}
else if(numbers[middle] == target)
{
break;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
if(low == -1 || numbers[low]!=target)
{
low=-1;
return low;
}
else
{
return low;
}
}
And here is part of the code which asks users for an input:
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(System.in);
int [] numbers = new int [50000];
int target;
int count=0;
try
{
BufferedReader br = new BufferedReader(new FileReader("randNums.txt"));
for(int i=0;i<50000;i++)
{
numbers[i]=Integer.parseInt(br.readLine());
}
br.close();
Arrays.sort(numbers);
System.out.print("Choose a number between 1-100000000 to search for: ");
target = Integer.parseInt(input.readLine());
int low = search(numbers, target, count);
if(low==-1)
{
System.out.println("The number was not on the list.");
}
else
{
System.out.println("The number is at position " + low);
System.out.println("It took " + count + " comparisons to find the number.");
}
}
Your search function has some issues. The implementation of the binary search in the search function should be like this:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length-1;
int low = 0;
int middle = (high+low)/2;
while(high>=low)
{
count++;
middle = (high+low)/2;
if(numbers[middle]==target)
{
return middle;
}
else if(numbers[middle]<target)
{
low = middle+1;
}
else if(numbers[middle]>target)
{
high=middle-1;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
return -1;
}
I'm very new to binary search and I attempted a code that would read values from a document and then the user can input a number to search for from the document, and through binary search, the number would be found. I'm having trouble now because the "low" variable that I initialize in the binary search section of my code is not being returned to my main code and there's an error that says "low can not be resolved to a variable".
Here is the code for my binary search:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length;
int low = -1;
int middle = (high+low)/2;
while(high-low>1)
{
count++;
middle = (high+low)/2;
if(numbers[middle]>target)
{
high = middle;
}
else if(numbers[middle]<target)
{
low = middle;
}
else
{
break;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
if(low == -1 || numbers[low]!=target)
{
low=-1;
return low;
}
else
{
return low;
}
}
And here is the code from my main code. The part with the if statements is where the error is showing up:
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(System.in);
int [] numbers = new int [50000];
int target;
int count=0;
try
{
BufferedReader br = new BufferedReader(new FileReader("randNums.txt"));
for(int i=0;i<50000;i++)
{
numbers[i]=Integer.parseInt(br.readLine());
}
br.close();
Arrays.sort(numbers);
System.out.print("Choose a number between 1-100000000 to search for: ");
target = Integer.parseInt(input.readLine());
search(numbers, target,count);
if(low==-1)
{
System.out.println("The number was not on the list.");
}
else
{
System.out.println("The number is at position " + low);
System.out.println("It took " + count + " comparisons to find the number.");
}
}
You have to initialize low in main:
int low=search(numbers, target,count);
I have Already resolved this algorithm.
Try my code :
public static int guessNumber(int number) {
int first = 0;
int last = 1_000_000;
if (verify(first) == 0) {
count++;
return first;
}
if (verify(last) == 0) {
count++;
return last;
}
while (last > first && count <= 50) {
count += 1;
// get the middle of the range
int middle = (first + last) / 2;
if (verify(middle) == 0) {
return middle;
}
if (verify(middle) == 1) {
first = middle + 1;
if (verify(first) == 0) {
return first;
}
}else {
last = middle - 1;
if (verify(last) == 0)
return last;
}
}
return 0;
}
//Function verify(integer) => integer
public static int verify(int guess){
if (numberTobeGuessed > guess ) {
return 1;
}else if (numberTobeGuessed < guess) {
return -1;
}
return 0;
}
I recently found a solution for lazy peoples like me use below code
int position = Arrays.binarySearch(numbers , target);
here no need to sort, and array variable number integer variable target.
Hello there I am learning Java and after doing some tasks to learn recursion I was giving my self some exercises to learn it a bit more but now I am struggeling with some..
So the main Problem is that I dont know how I can multiply every element in an Array recursively when the elements in that array are object (Maybe there is at the end no difference if objects are in there or not). So the exercise I gave myself was: check if 1 / 3 is in the given Array. If Yes then multiply everything in that array with 2 / 1.
This is Fraction:
private int numerator; // Zaehler
private int denominator; // Nenner
public Fraction ( int num, int denom )
{
if ( denom != 0 )
{
if ( denom < 0 )
{
numerator = -num;
denominator = -denom;
}
else
{
numerator = num;
denominator = denom;
}
reduce();
}
else
{
// error: division by zero
throw new IllegalArgumentException();
}
}
public Fraction()
{
numerator = 0;
denominator = 1;
}
public Fraction( int num )
{
numerator = num;
denominator = 1;
}
So I got it done by doing it with an for loop:
public static Fraction[] mulWithFor(Fraction[] arr)
{
for (int i = 0; i<arr.length; i++)
{
arr[i] = arr[i].multiply(new Fraction(2,1));
}
return arr;
}
But thats not my Main goal I want to do it recursively so that was my approach:
public static Fraction[] mulAus(Fraction[] arr, int i)
{
if (i>= 0 && i<arr.length)
{
rekurMul(arr,i);
//return mulAus(rekurMul(arr,i-1));
}
return arr;
}
public static Fraction rekurMul(Fraction[] arr, int i)
{
if (i>= 0 && i<arr.length)
{
return arr[i].multiply(new Fraction(2,1));
return arr[i].multiply(new Fraction(2, 1)); // Does Not Work!!!
}
throw new IndexOutOfBoundsException();
}
Maybe there is someone who can Help me! Thank you for your attention.
OK Thanks to #Chaï Sarfati and also to the others trying to help me out. I now know how to multiply recursive things in an Array! I used the Methods from #Chaï Sarfati but wrote an alternative method for his "oneThirdIsPresent" which is also a recursive method : So now my working code looks like this
public static Fraction[] mulAus(Fraction[] arr)
{
if(contains(arr,arr.length-1,new Fraction(1,3)))
{
rekurMul(arr,0);
return arr;
}
throw new IllegalArgumentException("1/3 does not exist in the Input-Array");
}
public static void rekurMul(Fraction[] arr, int i)
{
if(i == arr.length)
{
return ;
}
arr[i] = arr[i].multiply(new Fraction(2,1));
rekurMul(arr,i+1);
}
The Method to check if 1 / 3 exists in the given Array.
public static boolean contains(Fraction[] arr, int i, Fraction x)
{
if (i>= 0 && i < arr.length)
{
if (arr[i].equals(x))
{ return true;}
else
{ return contains(arr, i-1,x); }
}
return false;
}
I hope other People can learn from the code.. Maybe there are better solutions but I am just starting Programming so I dont know them for now.
Bye
Assuming you have a multiplyBy(Fraction f) method that works properly in you Fraction class.
Moreover, it will be better (more readable, more time & space complexity saving) to do it iteratively.
For the sake of the example, I would do like this:
First define:
private static boolean oneThirdIsPresent(Fraction[] arr){
for (int i = 0; i < arr.length; i++) {
if(arr[i].numerator == 1 && arr[i].denominator == 3) {
return true;
}
}
return false;
}
private static void recursivelyMultBy2(Fraction[] arr, int index){
if(index == arr.length){
return;
}
arr[index] = arr[index].multiplyBy(new Fraction(2));
recursivelyMultBy2(arr, index+1);
}
In order to solve finally:
public static void multBy2IfOneThirdIsPresent(Fraction[] arr){
if(oneThirdIsPresent(arr)){
recursivelyMultBy2(arr, 0);
}else{
return;
}
}
Here's a quick example of just the recursive multiplication part:
public static void main(String[] args)
{
Fraction[] fractions = new Fraction[] {new Fraction(1,2), new Fraction(2,3), new Fraction(3,1)};
System.out.println("Fractions:");
for(Fraction f: fractions)
{
System.out.println(f);
}
System.out.println("Multiplying array by 2...");
Fraction.mulAus(fractions, new Fraction(2, 1));
for(Fraction f: fractions)
{
System.out.println(f);
}
}
Modified Fraction Class (multiplication code at the bottom):
public class Fraction
{
private int numerator; // Zaehler
private int denominator; // Nenner
public Fraction(int num, int denom)
{
if (denom != 0)
{
if (denom < 0)
{
numerator = -num;
denominator = -denom;
}
else
{
numerator = num;
denominator = denom;
}
reduce();
}
else
{
// error: division by zero
//throw new IllegalArgumentException();
}
}
private void reduce()
{
// ...
}
public Fraction()
{
numerator = 0;
denominator = 1;
}
public Fraction(int num)
{
numerator = num;
denominator = 1;
}
public String toString()
{
return numerator + " / " + denominator;
}
public void MultiplyBy(Fraction F)
{
if (F != null)
{
numerator = numerator * F.numerator;
denominator = denominator * F.denominator;
reduce();
}
}
public static void mulAus(Fraction[] arr, Fraction F)
{
if(arr != null && F != null)
{
rekurMul(arr, 0, F);
}
}
private static void rekurMul(Fraction[] arr, int i, Fraction F)
{
arr[i].MultiplyBy(F);
if (i < (arr.length - 1))
{
rekurMul(arr, ++i, F);
}
}
}
Output:
I already got the Towers of Hanoi with recursion, it's also working without any problems. But now I'd like to know how it could work without recursion but with stack instead.
public class Hanoirecursive {
static void move (
int x,
char start,
char help,
char aim) {
if (x == 1)
System.out.println(" from " + start + " to " + aim);
else {
move(x-1,start, aim, help);
System.out.println(" from " + start + " to " + aim);
move(x-1,help, start, aim);
}
}
public static void main (String args[]) {
int x = Integer.parseInt(args[0]);
if (x > 0) {
System.out.println("Movements: ");
move(x,'A','B','C');
}
else
System.out.println("No negative number.");
}
}
I would like to.. convert this code so it works with a stack and no longer with recursion but I really don't know where to start. Could you give me some hints please?
For the stack I could find this on the internet:
public class Stack {
private int[] stackElements;
private int top;
public Stack(int a) {
stackElements = new int[a];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int b) {
stackElements[++top] = b;
}
public int pop() {
if(isEmpty() ) {
System.out.println( "Empty stack" );
return -1;
}
else {
return stackElements[top--];
}
}
}
Any kind of help is very much appreciated! :)
I want to get an output that displays something like 1*2*3*4 but instead I get 4*3*2*1
this is my code:
public static int fact(int n)
{
if(n ==1)
return 1;
else
return n * fact(n-1);
}
public static int factorForm(int n)
{
System.out.print(n);
if (n == 1)
return 1;
else
{
System.out.print("*");
return n + '*' + factorForm(n-1);
}
}
You are calling fact(4)
Then you print
Then you call fact(3)
If you invert that you'll get what you want:
public class fact {
static int f(int n)
{
if (n ==1 )
{
System.out.print(1);
return 1;
}
int ret= (n * f(n-1));
System.out.print("*");
System.out.print(n);
return ret;
}
public static void main(String[] args)
{
int ret=f(4);
System.out.print("=");
System.out.println(ret);
}
}
To reverse the output, n should be printed after making the recursive call:
public static int factorForm(int n)
{
if (n == 1)
{
System.out.print(1);
return 1;
}
else
{
int rest = factorForm(n-1); // prints 1*2*...*n-1
System.out.print("*");
System.out.print(n);
return rest * n;
}
}
The expression n + '*' + factorForm(n-1) performs integer addition, not multiplication or string concatenation. I changed it to perform multiplication. If the intention is to return the string that was printed, the return type and the type of rest should be changed to String, the return value in the base case should be "1", and that expression should be changed to rest + "*" + n.
Return after printing as below, more importantly understand how recursion works:
public static int factorForm(int n)
{
if (n == 1){
System.out.print("1*");
return 1;
}
else
{
int val = n * factorForm(n-1);
System.out.print(n + "*");
return val;
}
}
if you want to get like 1*2*3*4 result. i think you can do this.
this is my code:
public static String fact(int n) {
if (n < 1) {
throw new RuntimeException("n must be int type and up 0");
}
else if (n == 1) {
return "1";
} else {
return n + "*" + fact(n - 1);
}
}
public static String factorForm(String str) {
String [] arr = str.split("\\*");
String [] newArr = new String[arr.length];
String result = "";
if (arr.length > 1) {
for (int i = 0; i < arr.length; i++) {
newArr[arr.length - i - 1] = arr[i];
}
for (int i = 0; i < newArr.length; i++) {
result += newArr[i] + (i != newArr.length - 1 ? "*" : "");
}
return result;
} else {
return str;
}
}
like this. you can get results what you get. may be complicated.