If you have any query feel free to chat us!
Happy Coding! Happy Learning!
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
.
Comments: 0