Benutzer-Werkzeuge

Webseiten-Werkzeuge

Übersetzungen dieser Seite:

projects:the_factorial_function_in_several_languages

The factorial function in several languages:

	   The factorial function takes a positive
	integer, and returns a positive integer.  Its
	value is the product of all the integers from
	one up to the value of the parameter.  It is
	normally written with a postfix exclamation
	point, thus:

			0! =  1
			1! =  1
			2! =  2
			3! =  6
			4! =  24
			5! = 120

	The factorial function is used in this example
	to illustrate a number of different programming
	languages.

8080 Assembler -- iterative

	;
	;	given n in A, returns n! in DE
	;	no warrantees, expressed or implied
	;	about any other returned register
	;	contents.
	;
	FACT:	LXI	DE,1
		ORA	A
		RZ
	F1:	CALL	MULT
		DEC	A
		JNZ	F1
		RET
	;
	;	MULTIPLY A BY DE, RESULT IN DE
	;
	MULT:	MOV	B,A
		MOV	A,D
		MOV	C,16
	M1:	SHL
		PUSH	A
		MOV	A,E
		RLC
		MOV	E,A
		POP	A
		JCC	M2
		ADD	B
	M2:	DEC	C
		JNZ	M1
		MOV	D,A
		MOV	A,B
		RET

8086 Assembler -- iterative

	;
	;	given n in cx, returns n! in dx:ax
	;	clobbers cx in the process
	;
	fact	proc
		mov	ax,1
		jcnz	f1
		ret
	f1:	mul	cx
		loop	f1
		ret
	fact	endp

IBM/PC Basic -- iterative, recursion not allowed

	10 REM  -- GIVEN N, RETURNS N! IN FACT
	15 REM     USES I AS TEMPORARY
	20 FACT=1
	30 IF N=0 THEN GOTO 70
	40 FOR I=1 TO N
	50 FACT=FACT*I
	60 NEXT I

FORTRAN -- iterative, recursion not allowed

	INTEGER FUNCTION FACT(N)
	FACT=1
	IF(N) 10,20,30
     30	DO 40 I=1,N
     40 FACT=FACT*I
     20 RETURN
     10 CALL ERROR
	END

COBOL -- iterative, recursion not allowed

	FACTORIAL-ROUTINE.
		MOVE ONE TO FACT.
		PERFORM FACTORIAL-LOOP VARYING I FROM ONE TO N.

	FACTORIAL-LOOP.
		MULTIPLY FACT BY I.

C -- iterative

	int fact(n)
	int n; {
	    int f=1;
	    while(n) f*=n--;
	    return(f);
	}

C -- recursive

	int fact(n)
	int n; {
	    return(n==0 ? 1 : n*fact(n-1));
	}

Forth -- iterative

	: FACT 1 SWAP 0 ?DO I * LOOP ;

Forth -- recursive

	: FACT ?IF DUP 1- RECUR * ELSE 1 THEN ;

APL -- iterative

	FACT <-- * / IOTA N

muLisp -- iterative

	(DEFUN FACT (LAMBDA (N F)
	    ((ZEROP N) 1)
	    (SETQ F 1)
	    (LOOP
		(SETQ F (TIMES F N))
		((ZEROP (SETQ N (SUB1 N))) F) ) ))

muLisp -- recursive

	(DEFUN FACT (LAMBDA (N)
	    ((ZEROP N) 1)
	    (TIMES N (FACT (SUB1 N))) ))

microProlog -- recursive, iteration not allowed

	((FACT 0 1))
	((FACT _N _F)
		(PLUS _M 1 _N)
		(FACT _M _G)
		(TIMES _N _G _F))

AML -- iterative

	fact: SUBR (%n);
		IF n EQ 0 THEN RETURN(1);
		f: NEW n;
		WHILE --n GT 1 DO f *= n;
		RETURN(f);
	END;

AML -- recursive

	fact: SUBR (n);
		RETURN(
		    IF n EQ 0 THEN 1
		    ELSE n * fact(n-1);
		);
	END;


	F1:	CALL	MULT
		DEC	A
		JNZ	F1
		RET
	;
	;	MULTIPLY A BY DE, RESULT IN DE
projects/the_factorial_function_in_several_languages.txt · Zuletzt geändert: 2013-06-06 21:27 (Externe Bearbeitung)