Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- public static void main(String[] args) {
- for (int i = 0; i < 20; i++) {
- System.out.println(fibR(i));
- }
- System.out.println("=============");
- for (int i = 0; i < 20; i++) {
- System.out.println(fibI(i));
- }
- }
- // Recursive fibonacci calculator
- public static int fibR(int n) {
- if (n < 0) {
- throw new IllegalArgumentException();
- } else if (n == 0) {
- return 0;
- } else if (n == 1) {
- return 1;
- } else {
- return fibR(n - 1) + fibR(n - 2);
- }
- }
- // Iterative fibonacci calculator
- public static int fibI(int n){
- if(n < 0){
- throw new IllegalArgumentException();
- } else if(n == 0){
- return 0;
- } else if(n == 1){
- return 1;
- } else {
- int a = 0;
- int b = 1;
- int c = 0;
- for (int i = 1; i < n; i++) {
- c = a + b;
- a = b;
- b = c;
- }
- return c;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement