1

I'm a beginner in programming trying to practice java and came across this problem (http://www.codeabbey.com/index/task_view/fibonacci-sequence). It ask's for the index of a certain fibonacci number. This is what was my orignal code

public static int fibonacciSequence(long n){
        int i = 1;
        long num1 = 0;
        long num2 = 1;
        while (num2 != n){

            long tempnum = num1;
            num1 = num2;
            num2 = tempnum +  num2;
            i++;
            if (n == 0){
                i = 0;
            }
        }
        return i;
    }

It works great in checking for checking the index of a fibonacci number, however some sample data are really long.

SampleData("60859646305146968781682860639833937855759700810919961259581748822691123490204305816372672244917896824842888612853501101254034489979476227") and eclipse takes to long to solve the problem. I found this code instead

public static int fibIndex(long n) {
        return (int) Math.round(Math.log(n * Math.sqrt(5))/Math.log(1.618));
    }

but cant seem to make it work. I read through here to use a BigInterger but i cant seem to implement it on my code. btw here is a code that is in javascript ("Index of a really big Fibonacci Number"). Can someone help me please

Community
  • 1
  • 1
Onedaynerd
  • 49
  • 2
  • 9
  • 1
    It might help to see an example: http://stackoverflow.com/questions/1783912/java-how-to-use-biginteger – Ryan Mar 30 '15 at 18:17
  • For starters, make sure your code handles non-Fibonacci input gracefully: check for negative numbers, terminate loop when generated value greater than input (or negative, using a number type that does overflow). For BigIntegers, Ryan's advice to consult example usage is valuable. With you stating neither what you tried nor what has been objectionable about the outcome, whether using BigIntegers or "reverse Moivre-Binet", help is going to be difficult. – greybeard Apr 19 '15 at 18:05

0 Answers0