67 Fibonacci Sequence


Back to General discussions forum

Brenden Barker     2017-01-03 23:57:38

The program I wrote gives answers that are one less than the answer, but only when the itteration count is between 100-200. More than that it is correct, and less than it is too, just that range has issues. What are some reasons that this would occur? Below is what I have so far:

package fibonaccisequence;

import java.util.Scanner;

public class FibonacciSequence {

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    int length, itCount;
    double oldNum, newNum, tempNum, numIn;

    Scanner sc = new Scanner(System.in);
    System.out.println("Number of inputs: ");
    int count = sc.nextInt();

    for (int i=0; i<count; i++) {
        sc = new Scanner(System.in);
        System.out.println("Enter number to evaluate: ");
        numIn = sc.nextDouble();
        oldNum = 1;
        newNum = 0;
        itCount = 0;

        while (oldNum <= numIn){
            tempNum = oldNum;
            oldNum += newNum;
            newNum = tempNum;
            itCount++;
            System.out.println("Calculation running...");
        }
        System.out.println("Number completed, saving...");
        sb.append(itCount + " ");

    }
    System.out.println(sb);

}

}

Quandray     2017-01-04 07:56:06
User avatar

Hi Brendan,

I've never used Java, but it may be due to you using doubles.

The Fibonacci Sequence only contains integers, which get large quickly, while doubles hold floating point numbers. As the numbers get bigger, a double won't be able to hold the exact value and this problem is about looking for exact values.

You need to find a way of dealing with the exact value of large integers (and that's easier in Java than some other languages).

Brenden Barker     2017-01-05 20:16:36

Alrighty then, I'll look into that, thanks for the tip!

Quandray     2017-01-05 21:32:05
User avatar

If you get stuck, please ask again.

Please login and solve 5 problems to be able to post at forum