Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use BigInteger with an array?

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.

like image 770
Kevin Ossia Avatar asked Mar 21 '13 03:03

Kevin Ossia


1 Answers

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

like image 127
Saurabh Avatar answered Oct 15 '22 09:10

Saurabh