Fibonacci numbers using Big Integers

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 76:-  Fibonacci numbers using Big Integers

To calculate Fibonacci numbers using BigInteger in Java, you can use a loop or recursion. Here's an example using a loop to generate Fibonacci numbers:

javaCopy code

import java.math.BigInteger; public class FibonacciWithBigInteger {    public static void main(String[] args) {        int n = 50; // Number of Fibonacci numbers to generate        // Generate and print Fibonacci numbers        for (int i = 0; i < n; i++) {            BigInteger fibonacciNumber = fibonacci(i);            System.out.println("Fibonacci(" + i + "): " + fibonacciNumber);        }    }    public static BigInteger fibonacci(int n) {        BigInteger a = BigInteger.ZERO;        BigInteger b = BigInteger.ONE;        if (n == 0) {            return a;        } else if (n == 1) {            return b;        } else {            for (int i = 2; i <= n; i++) {                BigInteger next = a.add(b);                a = b;                b = next;            }            return b;        }    } }

In this example, we create a method fibonacci that calculates the nth Fibonacci number using BigInteger. We initialize a and b to BigInteger.ZERO and BigInteger.ONE, respectively. Then, we use a loop to calculate the Fibonacci numbers from 0 to n. Each Fibonacci number is the sum of the previous two numbers (a and b), and we update the values of a and b accordingly.

The main method calls the fibonacci method to generate and print the first n Fibonacci numbers.

Note that BigInteger allows you to handle large Fibonacci numbers that may not fit into primitive data types like int or long.

12. Advanced

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support