import java.math.*; import java.io.*; public class FibonacciStack { private static BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) ); private static int count = 0; // just to make the printing prettier // This is the classic, recursive implementation of a function // that computed the nth Fibonacci number (given n) public static int fibonacci(int n) { myStack S1 = new myStack(n+1); myStack S2 = new myStack(n+1); S1.push(n); S2.push(1); count++; for(int i = 0; i < count; i++) System.out.print(" "); System.out.println("push " + n); while(!S1.isEmpty()) { long value = S1.pop(); long visitNumber = S2.pop(); // Reached a base case. The item that was popped is not pushed back if((value == 1) || (value == 2)) { for(int i = 0; i < count; i++) System.out.print(" "); System.out.println("pop"); count--; continue; } // This is the first visit to this record after it was created. // It is now time make and push a record with value-1 if(visitNumber == 1) { S1.push(value); S1.push(value-1); // Print out the newly pushed item count++; for(int i = 0; i < count; i++) System.out.print(" "); System.out.println("push " + (value-1)); S2.push(2); S2.push(1); } // This is the second visit to this record after it was created. // It is now time make and push a record with value-2 if(visitNumber == 2) { S1.push(value); S1.push(value-2); // Print out the newly pushed item count++; for(int i = 0; i < count; i++) System.out.print(" "); System.out.println("push " + (value-2)); S2.push(3); S2.push(1); } // This is the third and final visit to this record after it was created. // It is now time to get rid of this record, by not pushing it back if(visitNumber == 3) { for(int i = 0; i < count; i++) System.out.print(" "); System.out.println("pop"); count--; } } // end while return 0; // this does not really compute anything; just simulates // the behavior of the system stack } public static void main(String[] args) { int n; long time, newTime, answer; // Prompt the user System.out.println("Type a positive integer." ); try{ // Read a line of text from the user. String input = stdin.readLine(); // converts a String into an int value n = Integer.parseInt( input ); time = System.currentTimeMillis(); answer = fibonacci(n); newTime = System.currentTimeMillis(); System.out.println("The "+n+"th Fibonacci number is "+ answer); System.out.println("It took " + (newTime-time) + " milliseconds to compute it."); } catch(java.io.IOException e) { System.out.println(e); } } // end of main } // end of class