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

haskell

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

re = readline.to_i
(1 .. re).each{
	n = readline.to_i
	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
read re
for ri in `seq $re`
do
	read n
	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))
	   (display (factorial (read)))
	   (newline)))))

(gao (read))
15 Responses to “Small factorials”
  1. dd says:

    那个ruby若写成 readline.to_i.times 看上去和谐很多

  2. Navi says:

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

    • watashi says:

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

      • Navi says:

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

        • Navi says:

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

  3. owen_water says:

    表示最近就在上一门haskell的课~上的云里雾里~

  4.  
Leave a Reply