Problem:
Create a Fibonnaci program in java that calculate the fibbonaci numbers using BigInteger class. Include also iterative and recursive methods for the sake of comparaison.
Output:
Enter a positive int value (q to quit):
40
Iterative Fibonacci: 102334155
Recursion Fibonacci: 102334155
Duration: 2088
Accurate Fibonacci: 102334155
Enter a positive int value (q to quit):
q
40
Iterative Fibonacci: 102334155
Recursion Fibonacci: 102334155
Duration: 2088
Accurate Fibonacci: 102334155
Enter a positive int value (q to quit):
q
Solution:
import java.math.BigInteger; import java.util.Scanner; public class FibonacciApp { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n; String n_str; long fib_iter, fib_rec, time_in, time_out; BigInteger fib_acc; System.out.println("Enter a positive int value (q to quit):"); n_str = scan.nextLine(); while(!n_str.equalsIgnoreCase("q")) { try { n = Integer.parseInt(n_str); fib_iter = fibonacci_iter(n); System.out.println("Iterative Fibonacci: " + fib_iter); time_in = System.currentTimeMillis(); fib_rec = fibonacci_rec(n); System.out.println("Recursion Fibonacci: " + fib_rec); time_out = System.currentTimeMillis(); System.out.println("Duration: " + (time_out-time_in)); fib_acc = fibonacci_acc(n); System.out.println("Accurate Fibonacci: " + fib_acc); } catch (NumberFormatException e) { System.out.println("Input must be numeric. Try Again"); } System.out.println("Enter a positive int value (q to quit):"); n_str = scan.nextLine(); } } private static long fibonacci_iter(int n) { if (n==0 || n==1) return n; else { long previousprev = 0; long prev =1; long current = 1L; for (int i=2 ; i <=n ; i++) { current = previousprev + prev; previousprev = prev; prev = current; } return current; } } private static long fibonacci_rec(int n) { if (n ==0 || n==1 ) return n; else return fibonacci_rec(n-1) + fibonacci_rec(n-2) ; } private static BigInteger fibonacci_acc(int n) { if (n==0 || n==1) return BigInteger.valueOf(n); else { BigInteger prevprev = BigInteger.ZERO; BigInteger prev = BigInteger.ONE; BigInteger current = BigInteger.ONE; for (int i = 2; i <= n ; i++) { current = prevprev.add(prev); prevprev = prev; prev = current; } return current; } } }
liposuction Korea's #1 Liposculpture Clinic. Lydian plastic surgery is the home of VIP patients. Celebrities, Influencers and Diplomats all know and trust Doctor An and Lydian plastic surgery clinic to provide detailed results.
ReplyDelete