1

An integer value N is passed as the input. The program must print the first N terms in the Fibonacci sequence.

import java.util.Scanner;
public class FibonacciExample {
 
    public static void main(String[] args) 
    {
    
         int maxNumber = 0; 
         int previousNumber = 0;
         int nextNumber = 1;
         
            System.out.println("How many numbers you want in Fibonacci:");
            Scanner scanner = new Scanner(System.in);
            maxNumber = scanner.nextInt();
            System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
 
            for (int i = 1; i <= maxNumber; ++i)
            {
                System.out.print(previousNumber+" ");
                /* On each iteration, we are assigning second number
                 * to the first number and assigning the sum of last two
                 * numbers to the second number
                 */
 
          
                int sum = previousNumber + nextNumber;
                previousNumber = nextNumber;
                nextNumber = sum;
            }
 
    }
 
}

As here the code works fine for below 30 Numbers . But after 30 It showing the negative values which i don't need For eg If i want

5

Number of fibonacci series it showing perfect solution

0 1 1 2 3

But if Im giving

48

It showing

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 **-1323752223** 

But I need this answer

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 **2971215073**

SEE THE LAST NUMBER .I have also tried long but didn't result in .So what Can i do to achieve that Output . Thanks In Advance

Develper
  • 57
  • 3
  • 11

1 Answers1

1

The Integer.MAX_VALUE is 2147483647.

Your maximum value expected is 2971215073, which is higher than this.

If you need to get higher numbers, use long like this:

    int maxNumber = 0;
    long previousNumber = 0;
    long nextNumber = 1;

    //...
        long sum = previousNumber + nextNumber;
    //...
csalmhof
  • 1,820
  • 2
  • 15
  • 24