import java.io.*;
class machematics{//Iterative approach
int fibonacci(int n){
if(n==0){
return 0;
}
else if(n==1){
return 1;
}
else
{
int a=0,b=1,c = 0;
for(int i=2;i<=n;i++){
c=a+b;
a=b;
b=c;
}
return c;
}
}
}
public class FibonacciIterative {
public static void main(String[] args) throws IOException{
machematics m= new machematics();
BufferedReader br =new
BufferedReader(new InputStreamReader(System.in));
System.out.print("請輸入n:");
int n=Integer.parseInt(br.readLine());
System.out.println("Fibonacci數列第"+n+"項:"+m.fibonacci(n));
}
}
沒有留言:
張貼留言