階乗 (n! = ?)

D 言語で 階乗を計算する.

モジュールを用いない

factorial.d

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/+
  Program: factorial.d
  Comment: Recursion for Factorial
  Compiler Version: Digital Mars D Compiler v2.049
  Build It: dmd -w factorial.d
  Runtime Environment: Snow Leopard 10.6.4
  Date: Sep 25th, 2010
  Author: Fei Zhao
  All Rights Reserved
+/

import std.stdio;

const int LIMIT = 10;

int fac(int n){
  if(n == 0)
    return 1;
  else
    return n * fac(n-1);
}

void main(){
  for(int i = 0; i <= LIMIT; i++ ){
    writefln("%2d! = %7d", i, fac(i));
  }
}

facotorial.d の実行結果は:

[cactus:~/code_d/algo]% ./factorial
 0! =       1
 1! =       1
 2! =       2
 3! =       6
 4! =      24
 5! =     120
 6! =     720
 7! =    5040
 8! =   40320
 9! =  362880
10! = 3628800

モジュールを用いる

recursion.d (モジュール)

1
2
3
4
5
6
7
8
module recursion;

public int fac(int n){
  if(n == 0)
    return 1;
  else
    return n * fac(n-1);
}

fac_main.d (主関数)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/+
  Program: fac_main.d
  Comment: Recursion for Factorial
  Compiler Version: Digital Mars D Compiler v2.049
  Build It: dmd -w fac_main.d recursion.d
  Runtime Environment: Snow Leopard 10.6.4
  Date: Sep 25th, 2010
  Author: Fei Zhao
  All Rights Reserved
+/

import std.stdio;
import recursion;

const int LIMIT = 10;

void main(){
  for(int i = 0; i <= LIMIT; i++ ){
    writefln("%2d! = %7d", i, fac(i));
  }
}

fac_main.d の実行結果は:

[cactus:~/code_d/algo]% ./fac_main
 0! =       1
 1! =       1
 2! =       2
 3! =       6
 4! =      24
 5! =     120
 6! =     720
 7! =    5040
 8! =   40320
 9! =  362880
10! = 3628800

Table Of Contents

Previous topic

再帰 (recursion)

Next topic

Java