Posted By

DrPepper on 01/26/11


Tagged

loop for


Versions (?)

[Java] CH6 Fibonacci Number Calculator


 / Published in: Java
 

  1. /**
  2.   the fibonacci sequence is defined by the following rule. the first two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. For example, the third value is 1 + 1 = 2, the fourth value is 1+2=3, and the fifth is 2+3 =5. If fn denotes the n the value in the fibonacci sequence, then
  3.   f1 = 1
  4.   f2 = 1
  5.   fn = fn-1 + f2-2 if n > 2
  6.   write a programing that prompts the user for n and prints the first n values in the fibonacciGenerator with a methof nextNumber.
  7. Hint: there is no need to store all values for fn you only need the last two values to compute the next one in the series:
  8.   fold1 = 1;
  9.   fold2 = 1;
  10.   fnew = fold1 + fold2
  11.   after that, discard fold2,which is no longer needed, and set fold2 to fold1 and fold1 to fnew.
  12.   your generator class will be tested with this runner program:
  13.  
  14.   public class FibonacciRunner
  15.   {
  16.   public static void main(String[] srgs)
  17.   {
  18.   Scanner in = new Scanner(System.in);
  19.   System.out.println("Enter n : ");
  20.   int n = in.nextInt();
  21.   fibonacciGenerator fg = fibonacciGenerator();
  22.  
  23.   for(int i = 1; i<= n; i++)
  24.   System.out.println(fg.nextNumber());
  25.   }
  26.   }
  27. */
  28. import java.util.Scanner;
  29.  
  30. public class Fib
  31. {
  32.  
  33. public static int fold1;
  34. public static int fold2;
  35. public static int fnew;
  36.  
  37. public Fib()
  38. {
  39. fold1 = 0;
  40. fold2 = 1;
  41. }
  42.  
  43. public static int nextNumber()
  44. {
  45. fnew = fold1 + fold2;
  46. return fnew;
  47. }
  48.  
  49. public static void deleteNumber()
  50. {
  51. fold1 = fold2;
  52. fold2 = fnew;
  53. }
  54.  
  55. public static void main(String[] srgs)
  56. {
  57. Fib fb = new Fib();
  58. Scanner in = new Scanner(System.in);
  59. System.out.println("Enter n : ");
  60. int n = in.nextInt();
  61. System.out.println("*** Fibonacci Numbers ***");
  62. for(int i = 1; i<= n; i++)
  63. {
  64. int nextNum = nextNumber();
  65. System.out.println(nextNum);
  66. deleteNumber();
  67. }
  68.  
  69. }
  70. }

Report this snippet  

You need to login to post a comment.