Примеры реализации функции факториал
Материал из Викиучебника
[править] Рекурсивные методы
Пример реализации рекурсивной функции для вычисления функции факториал.
[править] На языке Pascal
function fact(n : integer) : longint; begin if n <= 1 then fact := 1 else fact := n * fact(n - 1) end;
[править] На языке C++
unsigned long fact(unsigned int n) { if(n <= 1) return 1; return n * fact(n - 1); }
[править] На языке Lisp
(defun factorial (n) (if (= n 0) 1 (* (factorial (- n 1)) n)))
[править] На языке Forth
: square dup * ; : factorial ( n -- n! ) dup 0= if drop 1 else dup 1- recurse * endif ;
[править] На языке Scheme
(define (factorial n) (if (= n 0) 1 (* n (factorial (- n 1)))))
[править] На языке Ruby
def factorial n n <= 1 ? 1 : n * factorial(n - 1) end
[править] На языке PHP
function factorial($n) { return ($n <= 1) ? 1 : $n * factorial($n - 1); }
[править] На языке Perl
#!/usr/bin/perl sub factorial { my $n = shift; if ($n==0) { return 1; } else { return $n*factorial($n-1); } } print factorial(shift);
[править] На языке Simula
integer procedure factorial (n); integer n; factorial := if n=0 then 1 else n*factorial(n-1); begin integer n; n:=10 outint(n,5); outtext("! = "); outint(factorial(n),10); outimage; end
[править] На языке Smalltalk
factorial
"Answer the factorial of the receiver."
1/>self = 0 ifTrue: [^ 1].
1/>self > 0 ifTrue: [^ 1/>self * (1/>self - 1) factorial].
1/>self error: ’Not valid for negative integers’
[править] На языке Algol 68
PROC factorial = (INT n) INT: BEGIN IF n=0 THEN 1 ELSE n*factorial(n-1) FI END; print (factorial(10))
[править] На языке Ada
with Ada.Text_IO, Ada.Integer_Text_IO; use Ada; procedure Factorial is begin declare function Factorial (N: Integer) return Integer is begin if N=0 then return 1; else return N*Factorial(N-1); end if; end Factorial; begin Text_IO.Put ("10! = "); Integer_Text_IO.Put (Factorial(10)); Text_IO.New_Line; end; end Factorial;
[править] На языке LaTeX
\documentclass{article} \usepackage{ifthen} \newcounter{multi} \newcounter{multa} \newcommand{\mult}[2]{ \setcounter{multi}{1} \setcounter{multa}{#1} \whiledo{\themulti < #2}{ \addtocounter{multa}{#1} \stepcounter{multi} } } \newcounter{faki} \newcounter{faka} \newcommand{\fac}[1]{ \setcounter{faka}{1} \setcounter{faki}{2} \whiledo{\thefaki < #1}{ \mult{\thefaka}{\thefaki} \setcounter{faka}{\themulta} \stepcounter{faki}} \mult{\thefaka}{\thefaki} \themulta} \begin{document} \Huge $10!=\fac{10}$ \end{document}
[править] На языке Java
import java.math.BigInteger; public class Factorial { private static final BigInteger ZERO = new BigInteger("0"); private static final BigInteger ONE = new BigInteger("1"); public static BigInteger factorial (BigInteger n) { if (n.equals(ZERO)) return ONE; else return n.multiply(factorial(n.subtract(ONE))); } public static void main (String[] args) { BigInteger input = new BigInteger(args[0]); System.out.println (factorial(input)); } }
[править] На языке JavaScript
<html> <body> <script> function factorial (n) { if (n==0) return 1; else return n*factorial(n-1); } var n = prompt("N", "10"); document.write(n+"! = " + factorial(n)); </script> </body> </html>
[править] На языке Python
def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1)
[править] На языке Refal
Factorial {
0 = 1;
s.Value = <Mul s.Value <Factorial <Sub s.Value 1>>>;
}
[править] На языке Haskell
factorial :: Integer -> Integer factorial 0 = 1 factorial n | n > 0 n*factorial(n-1) | n < 0 error "---"
[править] Нерекурсивные методы
Пример реализации нерекурсивной функции для вычисления факториала
[править] На языке Pascal
function factorial(n : integer) : longint; var i : integer; f : longint; begin if n <= 1 then factorial := 1 else begin f := 1; for i := 2 to n do f := f * i; factorial := f end end;
[править] На языке C++
unsigned long factorial(unsigned int n) { if(n <= 1) return 1; unsigned long f = 1; for(unsigned int i = 2; i <= n; ++i) f *= i; return f; }
[править] На языке Lisp
(defun factorial (n) (if (< n 1) 1 (do ((f 1) (i 2 (1+ i))) ((> i n) f) (setq f (* f i)) ) ) )
[править] На языке Scheme
(define (factorial n) (define (iter n result) (if (= n 0) result (iter (- n 1) (* result n)))) (iter n 1))
[править] На языке Fortran
integer function fact (n) integer n fact = 1 do i = 1,n fact = fact * i enddo return end program factorial integer fact external fact n = 10 write (*,*) n,"! = ",fact(n) end program factorial
[править] На языке Unix Shell
#!/bin/sh result=1 for (( factor=$1 ; $factor ; factor=$factor-1 )) do let -i result=$result*$factor done echo $result
[править] На языке PHP
function factorial($n) { $result = 1; for ($i=2; $i<=$n; $i++) $result *= $i; return $result; }
[править] На языке Cobol
identification division.
program-id. factorial.
environment division.
data division.
working-storage section.
77 result pic 9(8).
77 n pic 9(8).
77 i pic 9(8).
procedure division.
main-line.
display "Enter a positive number: " with no advancing
accept n
move 1 to result.
perform varying i from 1 by 1 until i>n
multiply result by i giving result
end-perform
display "Factorial(" n ")= " result
stop run.
[править] На языке Basic
input "N = "; n f=1 for i = 1 to n f=f*i next i print n;"! = ";f
[править] На языке «Электроники МК-152» и советских ПМК
00.ВП 01.П0 02.1 03.ИП0 04.x 05.FL0 06.03 07.С/П 08.КБП0
[править] На языке AT&T x86 Assembler
factorial.s: .globl factorial factorial: movl $1, %eax jmp .L2 .L3: imull 4(%esp), %eax decl 4(%esp) .L2: cmpl $1, 4(%esp) jg .L3 ret factorial-main.c: #include <stdio.h> extern int factorial (int n); int main () { int n = 10; printf ("%d! = %d\n", n, factorial (n)); } gcc factorial-main.c factorial.s
[править] На языке Refal+
$func Factorial s.n = s.fact;
Factorial s.n =
1 s.n $iter <Mult s.fact s.n> <Sub s.n 1> :: s.fact s.n,
s.n : 0 =
s.fact;
[править] На языке Python
def factorial(x): return 0 if x==0 else reduce(lambda x,y:x*y,xrange(1,x+1))
[править] На языке Ruby
def factorial n f = 1 if n <= 1 1 else for i in 1..n f *= i end end end