fact(n) =1 : n=0 =n * fact(n-1) : n>0これで,すべてのnに対する fact(n) の値が求められます.たとえば
long Fact(long N) { long L; printf("in Fact(%d)\n", N); if (N == 0) return(1); else { L=N*Fact(N-1); printf("return fact=%ld\n",L); return(L); } } void main() { int Num; printf("number:"); scanf("%d",&Num); printf("\nfact(%d)= %ld \n",Num,Fact(Num)); }Fact(N) で Fact(N-1) を呼び出しています。このように、自分自身を呼び出すことを「再帰呼びだし」と言います。関数の先頭の long は倍精度の整数を値として返すことを指示します。long 型の整数は printf の書式では"%ld"とします。n!の値は急激に大きくなりますから、n に大きな値を与えるとオーバーフロ-して正しい値が求められなくなります。
#!/usr/bin/ruby #fact.rb def fact(n) return 1 if n ==0 f = 1 while n > 0 f *= n n -= 1 end return f end print fact(ARGV[0].to_i), "\n"
F(1)=F(2)=1, F(n)=F(n-1)+F(n-2) n≧3の時、このF(n)の計算は、単純な繰り返しでは計算できません(後で計算式を紹介します)。
long Fib(int N) { long L; //printf("in Fib(%d)\n",N); if (N==1 || N==2) return(1); else { L=Fib(N-1)+Fib(N-2); // printf("return Fib(%d)=%ld\n",N,L); return(L); } }
//フィボナッチ数列の計算 //Fibs.java import java.awt.*; import java.awt.event.*; import java.applet.*; public class Fibs extends Applet { int num; private TextField textField1 = new TextField(); private Button button1 = new Button(); private TextField textField2 = new TextField(); //アプレットの初期化 public void init() { try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } //コンポーネントの初期化 private void jbInit() throws Exception { textField1.setText("3"); textField1.setBounds(new Rectangle(28, 28, 97, 21)); this.setLayout(null); button1.setLabel("計算"); button1.setBounds(new Rectangle(43, 67, 77, 25)); button1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { button1_actionPerformed(e); } }); textField2.setText("textField2"); textField2.setBounds(new Rectangle(27, 109, 107, 25)); this.add(textField1, null); this.add(button1, null); this.add(textField2, null); } //計算ボタンが押された void button1_actionPerformed(ActionEvent e) { num=Integer.parseInt(textField1.getText());//数値をnumに読み込む textField2.setText(Long.toString(Fib(num)));//Fib(num)を表示する } //フィボナッチ数列の計算 long Fib(int N) { long L; //printf("in Fib(%d)\n",N); if (N==1 || N==2) return(1); else { L=Fib(N-1)+Fib(N-2); // printf("return Fib(%d)=%ld\n",N,L); return(L); } } }このファイルを Fibs.java で保存します。コンパイルは、コマンドプロンプトで
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> <title> HTML テストページ </title> </head> <body> フィボナッチ数列の計算Fibs<br> <applet codebase = "." code = "Fibs.class" name = "TestApplet" width = "200" height = "150" > </applet> </body> </html>これを、Fibs.class と同じフォルダに保存して、ダブルクリックします。ブラウザが立ち上がり、実行できます。