Search code examples
javafibonacci

How to figure out the largest Fibonacci number that my system can represent?


I'm asked to figure out the largest Fibonacci number that can be displayed on my system. Any idea how to go about that?


Solution

  • determine the largest fibonacci number that can be displayed on my system

    For that you need to use BigInteger

    Run this until your application stops because you have run out of resources.

    public static void main(String... args) {
        BigInteger a = BigInteger.ONE;
        BigInteger b = BigInteger.ONE;
        String last = null;
        try {
            for (long count = 1; ; count++) {
                BigInteger c = a.add(b);
                last = c.toString();
                a = b;
                b = c;
                if (count % 10000 == 0)
                    System.out.println("... " + count);
            }
        } catch (Throwable e) {
            System.out.println("The largest value which was calculated was");
            System.out.println(last);
        }
    }
    

    I would try it with a low amount of memory first e.g. -mx16m

    Update: Even with a limit of 16 MB, it has calculated 13K terms and still running.