fork download
  1. /* package so35398370; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class App {
  8. int fib(int n) {
  9. // Handle special case when n == 0
  10. if (n == 0) {
  11. return 0;
  12. }
  13. // General case, return the first of the
  14. // two values returned by fibaux
  15. else {
  16. return fibaux(n).getFirst();
  17. }
  18. }
  19.  
  20. // Auxiliary function
  21. // Return the nth and (n-1)th Fibonacci numbers
  22. // n must be an integer >= 1
  23. Pair fibaux(int n) {
  24. // Base case of for recursion
  25. if (n == 1) {
  26. return new Pair(1, 0);
  27. } else {
  28. // Recursive case
  29. Pair next = fibaux(n - 1);
  30. return new Pair(next.getFirst() + next.getSecond(), next.getFirst());
  31. }
  32. }
  33.  
  34. public static void main(String[] args) {
  35. App app = new App();
  36. System.out.println(app.fib(6));
  37. }
  38.  
  39. class Pair {
  40. private final int first;
  41. private final int second;
  42.  
  43. public Pair(final int first, final int second) {
  44. this.first = first;
  45. this.second = second;
  46. }
  47.  
  48. public int getFirst() {
  49. return this.first;
  50. }
  51.  
  52. public int getSecond() {
  53. return this.second;
  54. }
  55. }
  56. }
Success #stdin #stdout 0.1s 320512KB
stdin
Standard input is empty
stdout
8