Sunday 4 January 2015

Fibonacci Sequence (Part 3)

I wrote prog66 below to calculate a Fibonacci number supplied as a parameter then I tested it by recalculating the 20th term in the sequence:

andrew@UBUNTU:~/Java$ cat prog66.java
import java.math.BigInteger;
public class prog66
{
public static void main (String args[])
  {
  BigInteger x = BigInteger.valueOf(1);
  BigInteger y = BigInteger.valueOf(1);
  int required_term = Integer.parseInt(args[0]);
  int term = 0;
  boolean finished = false;
  while (!finished)
    {
    term++;
    if (term == required_term)
      {
      System.out.println(x);
      finished = true;
      }
    term++;
    if (term == required_term)
      {
      System.out.println(y);
      finished = true;
      }
    x = x.add(y);
    y = x.add(y);
    }
  }
}
andrew@UBUNTU:~/Java$ javac prog66.java
andrew@UBUNTU:~/Java$ java prog66 20
6765
andrew@UBUNTU:~/Java$
 

Then I ran the UNIX date command to check the time, calculated the 1,000,000th term in the Fibonacci sequence and ran the UNIX date command again. This showed that the program had taken less than 5 minutes to work out the answer:

andrew@UBUNTU:~/Java$ date;java prog66 1000000 > prog66.output;date
Sun Jan  4 19:31:40 GMT 2015
Sun Jan  4 19:36:23 GMT 2015
andrew@UBUNTU:~/Java$


I found a site which had the 1,000,000th Fibonacci number in a file called millionth-fibonacci-number.txt and downloaded it. Then I compared the first few digits in both files and saw that they were the same: 

andrew@UBUNTU:~/Java$ cat millionth-fibonacci-number.txt|more
1953282128707757731632014947596256332443542996591873396953405


andrew@UBUNTU:~/Java$ cat prog66.output|more
1953282128707757731632014947596256332443542996591873396953405