Created
November 18, 2020 11:53
-
-
Save zyryc/d1bf9df5306a6eb96c7e8dc8f96875a6 to your computer and use it in GitHub Desktop.
Fibocacci sequence recursively and by iteration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @author ruiyot | |
*/ | |
public class Fibonacci { | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
// System.out.println(fib(6)); | |
int i = 8; | |
for(int x=0; x<i; x++){ | |
System.out.println(fib(x)); | |
} | |
fibs(8); | |
} | |
private static int fib(int i) { | |
// solving recursively | |
if(i==0){ | |
return 0; | |
}else if(i==1){ | |
return 1; | |
}else{ | |
return(fib(i-1)+fib(i-2)); | |
} | |
} | |
private static void fibs(int i) { | |
int current = 1; | |
int prev = 0; | |
//solving qith iteralion | |
for(int x=0; x<i; x++){ | |
current = current + prev; | |
int las = prev; | |
System.out.println(current + " "); | |
prev = current; | |
current = las; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment