Примеры реализации функции факториал
Материал из Викиучебника
Содержание |
[править] Рекурсивные методы
Примеры реализаций рекурсивных функций для вычисления факториала.
[править] Pascal
function fact(n : integer) : longint; begin if n <= 1 then fact := 1 else fact := n * fact(n - 1); end;
[править] C/C++
int factorial(int n) { return !n ? 1 : n * factorial(n - 1); }
[править] Common Lisp
(defun factorial (n) (if (= n 0) 1 (* (factorial (- n 1)) n)))
[править] Forth
: factorial ( n -- n! ) dup 0= if drop 1 else dup 1- recurse * endif ;
[править] Scheme
(define (factorial n) (if (= n 0) 1 (* (factorial (- n 1)) n)))
[править] Ruby
def factorial n n > 1 ? n * factorial(n - 1) : 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."
self = 0 ifTrue: [^ 1].
self > 0 ifTrue: [^ self * (self - 1) factorial].
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
public int fact(int num) { return (num == 0) ? 1 : num * fact(num - 1); }
[править] JavaScript
function factorial (n) { return !n ? 1 : n * factorial(n-1); }
[править] CoffeeScript
factorial = (n) -> !n and 1 or n * factorial(n - 1);
[править] Python
def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1)
или
factorial = lambda x: factorial(x - 1) * x if x > 1 else 1
[править] Refal
Factorial {
0 = 1;
s.Value = <Mul s.Value <Factorial <Sub s.Value 1>>>;
}
[править] Haskell
factorial :: Integer -> Integer factorial n | n < 0 = error "factorial is not defined for negative numbers" | n == 0 = 1 | otherwise = n * fac (n - 1)
или
factorial :: Integer -> Integer factorial n = product [1..n]
[править] D
long Factorial(int n) { if (n <=1) return 1; return n * Factorial(n - 1); }
[править] Нерекурсивные методы
Примеры реализаций нерекурсивных функций для вычисления факториала.
[править] Pascal
function factorial(n : integer) : longint; var i : integer; f : longint; begin f := 1; for i := 2 to n do f := f * i; factorial := f end;
[править] C/C++
int factorial(int n) { int result = 1; for ( int i = 2; i <= n; i++ ) { result *= i; } return result; }
[править] Java
public int factorial(int num) { int fact=1; for (int i=1; i<=num; i++) { fact=i*fact; } return fact; }
[править] JavaScript
function factorial (n) { var res = 1; while(n) res *= n--; return res; }
[править] CoffeeScript
factorial = -> res = 1 while n then res *= n-- return res; }
[править] 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.П0 01.1 02.ИП0 03.x 04.FL0 05.02 06.С/П 07.БП 08.00
[править] 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;
[править] Ruby
def factorial n (1..n).inject(:*) end
Без итераторов:
def factorial n f = 1 if n <= 1 1 else for i in 1..n f *= i end end f end
[править] Python
def factorial(x): return 1 if x==0 else reduce(lambda x,y:x*y,xrange(1,x+1))
[править] J
factorial=: */@(>:@i.)
[править] Haskell
factorial :: Integer -> Integer factorial n | n < 0 = error "factorial is not defined for negative numbers" | otherwise = iter 1 n where iter result 0 = result iter result x = iter (result * x) (x - 1)
[править] Brainfuck
++++++++.! = [>+>+<[>>+<<-]>[>[>+>+<<-]<->>>[<<+>>-]<<<]>[<<+>>-]>[<<+>>-]<<-<<-]>>+.