Skip to content

Instantly share code, notes, and snippets.

@zyryc
Created November 18, 2020 11:53
Show Gist options
  • Save zyryc/d1bf9df5306a6eb96c7e8dc8f96875a6 to your computer and use it in GitHub Desktop.
Save zyryc/d1bf9df5306a6eb96c7e8dc8f96875a6 to your computer and use it in GitHub Desktop.
Fibocacci sequence recursively and by iteration
/**
*
* @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