5

I'm working on altering my Fibonacci sequencer so that the numbers after reaching ~100th term don't wrap around and become negative. How do I use BigInteger in this code that I wrote:

package me.kevinossia.mystuff;

import java.util.Scanner;

public class FibonacciDisplayer 
{
public static void main(String[] args)
{

    Scanner input = new Scanner(System.in);
    int total;
    System.out.print("This is a Fibonacci sequence displayer.\nHow many numbers would you like it to display?");
    total = input.nextInt();
    long[] series = new long[total];
    series[0]=0;
    series[1]=1;

    for(int i=2;i<total;i++)
    {
        series[i]=series[i-1] + series[i-2];
    }
    for(int j=0; j<total; j++)
    {
        System.out.print(series[j] + "\n");
    }
    input.close();
}
}

I've searched google high and low and I can't find anything specific to my case.

Kevin Ossia
  • 179
  • 1
  • 3
  • 9

2 Answers2

6

If you are sure that you only want to use BigInteger then you should think of creating array of BigInteger. So like

BigInteger[] series = new BigInteger[total];
series[0]=BigInteger.ZERO;
series[1]=BigInteger.ONE;

and in loop do
series[i] = series[i-1].add(series[i-2])

See this add API

Saurabh
  • 7,894
  • 2
  • 23
  • 31
  • 1
    Thank you very much, except I am not familiar with ZERO and ONE. I saw them on the javadocs but it didn't say what they were, or at least I didn't see it. – Kevin Ossia Mar 21 '13 at 03:48
  • 2
    @KevinOssia If you are not familiar with that, simply put BigInteger.valueOf(0L); or BigInteger.valueOf(1L) should give u the same result – Adrian Shum Mar 21 '13 at 04:16
1

If total is also BigInteger, then

BigInteger total = new BigInteger("1000000000000000");
BigInteger[] series = new BigInteger[total.intValue()];
series[0] = BigInteger.ZERO;
series[1] = BigInteger.ONE;
series[i] = series[i-1].add(series[i-2]);
david_c
  • 227
  • 1
  • 9
Jay
  • 11
  • 1