Skip to content

Instantly share code, notes, and snippets.

@IgorKravchenko10
Created September 11, 2014 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IgorKravchenko10/638e85ff50ec1f55483c to your computer and use it in GitHub Desktop.
Save IgorKravchenko10/638e85ff50ec1f55483c to your computer and use it in GitHub Desktop.
Вычисление чисел Фибоначчи.
//Итерационный метод во много раз быстрее работает, чем рекурсивный и является более эффективным с точки зрения экономии ресурсов процессора.
import java.util.*;
public class fibonacci {
static Scanner scan=new Scanner(System.in);
public static void main(String[] args){
System.out.print("Enter size: ");
int n=scan.nextInt();
System.out.println("Choose method: recursion - 1 or iteration - 2");
int method=scan.nextInt();
if (method==1)
for(int i=0; i<n; i++)
System.out.print(recursion(i)+" ");
else if(method==2)
iteration(n);
}
private static int iteration(int n){
int a=-1, b=0, sum=0;
for (int i=0; i<n; i++){
sum=a+b;
a=b;
b=sum;
System.out.print(Math.abs((sum))+" ");
}
return Math.abs((sum));
}
private static int recursion(int i){
if (i<=0) return 0;
else if (i==1) return 1;
else if (i==2) return 2;
else {
return recursion(i-1) + recursion(i-2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment