Created
September 11, 2014 15:52
-
-
Save IgorKravchenko10/638e85ff50ec1f55483c to your computer and use it in GitHub Desktop.
Вычисление чисел Фибоначчи.
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
//Итерационный метод во много раз быстрее работает, чем рекурсивный и является более эффективным с точки зрения экономии ресурсов процессора. | |
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