Noth Schwa 的个人资料¡Por la cara!照片日志列表 工具 帮助
12月20日

El legado del Factorial

EDITO: Voy a cambiar el sangrado del código (a dos espacios) y añadir una cosita al final.

    Así es, hoy presentaremos esa función matemática que ha salido tantas veces que no sabemos si es amiga o enemiga, si es eterna o sólo inmortal. En todo caso, disponemos de muchas armas para enfrentarnos a ella. Yo diría que el factorial es a la recursividad lo que el "Hola mundo" es a la programación en general...
    En primer lugar, su definición matemática (si esto estuviera en condiciones podría poner símbolos bonitos, pero como no es así, hay que aguantarse).
    Se define el factorial para los números naturales n de forma que: factorial(n) = { 1 si n = 0 / n·factorial(n-1) si n > 0
    Bien, veamos cómo podemos atacarla (suponemos en todos los casos que la llamada se hace con n >= 0):

// En pseudolenguaje, entiéndase ! como una flecha hacia abajo y :< como pertenece)
FUNCIÓN factorial(!n:
INICIO
  SI n = 0 ENTONCES
    RESULTADO <- 1
  SINO
    RESULTADO <- n*factorial(n-1)
  FINSI
FIN

/* En C */
int factorial(int n)
{
  return n ? n*factorial(n-1) : 1;
}

% En Matlab
function y = factorial(n)
if n == 0
  y = 1;
else
  y = n*factorial(n-1);
end

*** En Maude
op factorial : Nat -> Nat .
var N : NzNat .
eq factorial(0) = 1 .
eq factorial(N) = N*factorial(N-1) .

; En ensamblador (sintaxis de Intel)
factorial proc near
  push bp
  mov bp,sp
  push bx
  push dx
  mov bx,ss:[bp+4]
  or bx,bx
  jnz c1
c2:  mov ax,1
  jmp fin
c1:  mov dx,bx
  dec bx
  push bx
  call factorial
  mov bx,dx
  mul bx
fin:  pop dx
  pop bx
  pop bp
  ret 2

// En Java
public static int factorial(int n){
  if(n == 0){
   return 1;
  }else{
    return n*factorial(n-1);
  }
}
; En ensamblador para el MIPS
Fact:  addi $sp,$sp,-8
  sw $ra,4($sp)
  sw $a0,0($sp)
  slti $t0,$a0,1
  beq $t0,$zero,L1
  addi $v0,$zero,1
  addi $sp,$sp,8
  jr $ra
L1:  addi $a0,$a0,-1
  jal Fact
  lw $a0,0($sp)
  lw $ra,4($sp)
  addi $sp,$sp,8
  mult $v0,$v0,$a0
  jr ra

(CSP o algo basado en su sintaxis, entiéndase :< como pertenece y <> como un cuadradito)
factorial = {n :< N -> [[ n = 0 -> res := 1 <> n > 0 -> res := n*factorial(n-1) ]]

-- En Haskell
factorial :: Integer -> Integer
factorial 0 = 1
factorial m@(n+1) = m*factorial n

% En Prolog
factorial(0,1).
factorial(N,F) :-
  N > 0
  N1 is N-1,
  factorial(N1,F1),
  F is N*F1.

-- En Ada
function factorial(n:integer) return integer is
res:integer;
begin
  if n = 0 then
    res := 1;
  else
    res := n*factorial(n-1);
  end if;
  return res;
end factorial;

(* Pascal-FC *)
function factorial(n:integer):integer; begin
  if n = 0 then
    factorial := 1
  else
    factorial := n*factorial(n-1);
  end;
end;

-- Y por último en Ada otra vez, pero esta vez iterativamente,
-- porque por algún motivo desconocido me fascinan los bucles
-- de Ada
function factorial(n:integer) return integer is
res:integer;
begin
  res := 1;
  for i in 1 .. n
  loop
    res := res*i;
  end loop;
  return res;
end factorial;

Y ahora para terminar de verdad de la buena, otra versión iterativa del factorial:
¡El factorial en Brainfuck (y sí, lo he hecho yo)
Esta versión calcula el factorial de 5 y escribe por pantalla el carácter 'x', cuyo código ASCII es... 5! = 120:
>+++++ Esto es el 5 (se puede cambiar)
[>+>+>+<<<-]>-[>>-[>+>+<<-]>>[<>-]<<<-]>>[<>-]<<<-]>.

评论 (6)

请稍候...
很抱歉,您输入的评论太长。请缩短您的评论。
您没有输入任何内容,请重试。
很抱歉,我们当前无法添加您的评论。请稍后重试。
若要添加评论,需要您的家长授予您相应权限。请求权限
您的家长禁用了评论功能。
很抱歉,我们当前无法删除您的评论。请稍后重试。
您已超过了一天之内允许提供的评论数上限。请在 24 小时后重试。
因为我们的系统表明您可能在向其他用户提供垃圾评论,您的帐户已禁用了评论功能。如果您认为我们错误地禁用了您的帐户,请联系 Windows Live 支持部门
完成下面的安全检查,您提供评论的过程才能完成。
您在安全检查中键入的字符必须与图片或音频中的字符一致。

若要添加评论,请使用您的 Windows Live ID 登录(如果您使用过 Hotmail、Messenger 或 Xbox LIVE,您就拥有 Windows Live ID)。登录


还没有 Windows Live ID 吗?请注册

没有名字发表:

Hi,Do you have used LCD monitors, second hand lcd monitors and second hand flat screens? Please go here:www.sstar-hk.com(Southern Stars).We are constantly buying re-usable LCD panels,LCD recycle.The re-usable panels go through strictly designed process of categorizing, checking, testing, repairing and refurbishing before they are re-used to make remanufactured LCD displays and TV sets.Due to our recent breakthrough in testing and repairing technology of LCD, we can improve the value for your LCD panels. website:www.sstar-hk.com[ggjfcihgfddfh]

9 月 30 日
没有名字发表:

Hi,Do you have used LCDs, used flat screens and secondhand LCDs? Please go here:www.sstar-hk.com(Southern Stars).We are constantly buying re-usable LCD panels and working for LCD recycling.The re-usable panels go through strictly designed process of categorizing, checking, testing, repairing and refurbishing before they are re-used to make remanufactured LCD displays and TV sets.Due to our recent breakthrough in testing and repairing technology of LCD, we can improve the value for your LCD panels.

Contact Us

E-mail:sstar@netvigator.com
website:www.sstar-hk.com

9 月 11 日
9 月 8 日
9 月 3 日
没有名字发表:
wow gold!All wow gold US Server 24.99$/1000G on sell! Cheap wow gold,wow gold -40452803833438
6 月 23 日
Sergio发表:
OMG, el factorial esta aquí. Hasta en Brainfuck!!! Que wapo el factorial en Brainfuck y en todos los demás lenguajes de programación también. : P

Saludos.
12 月 23 日

引用通告

此日志的引用通告 URL 是:
http://fizban87.spaces.live.com/blog/cns!F170A731903FCB2C!397.trak
引用此项的网络日志