SPOJ24. Small factorials[FCTRL2]就是阶乘计算加高精度运算。以下是用内置大数支持的perl, php, java, ruby, python, haskell, bash, scheme等语言实现的代码。

```main = interact \$ unlines . map (\i -> show \$ f !! read i) . tail . words
where f = scanl (*) 1 [1 ..]
```

### perl

```#!/usr/bin/perl -w

use strict;
use Math::BigInt lib => 'GMP';

my @f = ();
push @f, Math::BigInt->new(1);
for (my \$i = 1; \$i <= 100; ++\$i) {
push @f, \$f[\$#f]->copy()->bmul(\$i);
}
chomp(my \$re = <STDIN>);
for (my \$ri = 1; \$ri <= \$re; ++\$ri) {
chomp(my \$n = <STDIN>);
print "\$f[\$n]\n";
}
```

### php

```#!/usr/bin/php
<?
\$f = array("1");
for (\$i = 1; \$i <= 100; ++\$i) {
\$f[\$i] = bcmul(\$f[\$i - 1], \$i);
}
fscanf(STDIN, '%d', \$re);
for (\$ri = 1; \$ri <= \$re; ++\$ri) {
fscanf(STDIN, '%d', \$n);
echo "\$f[\$n]\n";
}
?>
```

### java

```import java.util.Scanner;
import java.math.BigInteger;

public class FCTRL2 {
static BigInteger[] fctrl;

static {
fctrl = new BigInteger[101];
fctrl[0] = BigInteger.ONE;
for (int i = 1; i < fctrl.length; ++i) {
fctrl[i] = fctrl[i - 1].multiply(BigInteger.valueOf(i));
}
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int re = in.nextInt();
for (int ri = 1; ri <= re; ++ri) {
int n = in.nextInt();
System.out.println(fctrl[n]);
}
}
}
```

### ruby

```#!/usr/bin/ruby

(1 .. re).each{
print (1 .. n).inject{|p, i| p *= i}, "\n"
}
```

### python

```#!/usr/bin/perl

f = []
f.append(1L)
for i in range(1, 101):
f.append(f[-1] * i)
re = input()
for ri in range(re):
n = input()
print f[n]
```

### bash

```#!/bin/bash

export BC_LINE_LENGTH=1024
for ri in `seq \$re`
do
seq -s '*' \$n | bc
done
```

### scheme

```(define (factorial n)
(if (= n 0)
1
(* n (factorial (- n 1)))))

(define (gao re)
(cond
((> re 0)
(begin
(gao (- re 1))
(newline)))))

```
15 Responses to “Small factorials”
1. dd says:

• watashi says:

re 我错了

2. Navi says:

bc什么的最不和谐了… 话说perl一般都use strict的么…

• watashi says:

一般都用么，良好的习惯……
不过如果要用到typeglob或者symbolic reference的时候就不会用了

• Navi says:

555 我最不良好了…
话说
&f();
会产生标量上下文… 这种情况都是标量比列表优先吗…

• Navi says:

囧.. 钻石操作符被吃掉了… f的参数是一个钻石… 因为钻石可以返回标量也可以返回列表么… 如果遇到一个地方既是标量上下文 又是列表上下文会怎么样… 我这里试了下是只读入了一行的样子……

• watashi says:

试试
sub f1(\$) { print @_ }
sub f2(@) { print @_ }
f1(<>);
f2(<>);

• Navi says:

-.- 这样就和谐了…. 可是会不会有其他两种都能接受的地方呢…

3. owen_water says:

• watashi says:

• owen_water says:

• watashi says:

• owen_water says: