Fibonacci Sequence
F(n) = F(n-1) + F(n-2) , n>=3
F(n) = 1 , n = 2 or 1
Factorial Function
F(n) = n * (n-1) * ... * 2 * 1 = n!
使用JAVA撰寫。以下為範例:
// Recursive.java
import java.io.*;
public class Recursive
{
public static void main (String[] args) throws IOException
{
BufferedReader buf;
String str;
int num;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please input a integer : ");
str=buf.readLine();
num=Integer.parseInt(str);
System.out.print("Factorial function: "+1);
for(int i=2;i<=num;i++)
System.out.print(" * "+i);
System.out.println(" = "+num+"! = "+fac(num));
System.out.print("Fibonacci sequence: ");
for(int i=1;i<=num;i++)
{
System.out.print("F["+i+"] = "+fibonacci(i)+",\t");
}
System.out.print("\n");
}
public static int fac(int n) // factorial function, n!
{
if(n==0)
return 1;
else
return n*fac(n-1);
}
public static int fibonacci(int n) //Fibonacci sequence
{
if(n==1||n==2)
return 1;
else
return fibonacci(n-1)+fibonacci(n-2);
}
}
輸入一個整數 n,計算出 fibonacci(n) 和 n! 的結果。
沒有留言:
張貼留言