Faktoriál

Faktoriál je funkce, jejímž argumentem je přirozené číslo n a výstupem je součin všech čísel menších nebo rovných n (v případě n = 0 je výsledkem 1). Faktoriál čísla n se značí n!.

Příklady

0! = 1
1! = 1
2! = 2 \cdot 1 = 2
3! = 3 \cdot 2 \cdot 1 = 6
4! = 4 \cdot 3 \cdot 2 \cdot 1 = 24
5! = 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 120
6! = 6 \cdot 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 720
7! = 7 \cdot 6 \cdot 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 5040
8! = 8 \cdot 7 \cdot 6 \cdot 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 40320
9! = 9 \cdot 8 \cdot 7 \cdot 6 \cdot 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 362880
10! = 10 \cdot9 \cdot 8 \cdot 7 \cdot 6 \cdot 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1= 3628800

Kód

   /**
     * Vypocita faktorial cisla
     * @param number cislo >= 0
     * @return faktorial cisla
     */
    public static int factorial(int number) {
        if (number < 0) throw new IllegalArgumentException("zaporny argument");
        int result = 1;
        for (int i = number; i > 1; i--) {
            result *= i;
        }
        return result;
    }
    /**
     * Vypocita rekurzivne faktorial cisla
     * @param number cislo >=0
     * @return faktorial cisla
     */
    public static int factorialRek(int number) {
        if (number < 0) throw new IllegalArgumentException("zaporny argument");
        if (number == 0 || number == 1) return 1;
        return number * factorialRek(number - 1);
    }
/**
 * Vypocita faktorial vstupniho cisla
 * @param $number Vstupni cislo
 * @return Faktorial vstupniho cisla
 * @author Thomas (www.adamjak.net)
 */

function faktorial($number) {
    if ($number < 0) {
        die("zaporny argument");
    }
    $result = 1;
    for ($i = $number; $i > 1; $i--) {
        $result *= $i;
    }
    return $result;
}


/**
 * Vypocita faktorial vstupniho cisla rekurzivni formou algoritmu
 * @param $number Vstupni cislo
 * @return Faktorial vstupniho cisla
 * @author Thomas (www.adamjak.net)
 */

function faktorial_rek($number) {
    if ($number < 0) {
        die("zaporny argument");
    }
    if ($number == 0 || $number == 1) {
        return 1;
    }
    return $number * faktorial_rek($number - 1);
}
(defun fact (x)
"generates factorial of x"
(if (= x 0)
   1
   (* x (fact (- x 1)))))

(defun fact2 (x)
"generates factorial of x"
(if (zerop x)
   1
   (* x (fact2 (1- x)))))

(defun fact3 (x)
"generates factorial of x"
(cond ((zerop x) 1)
       (T (* x (fact3 (1- x))))))
{ zpětná vazba }
Delicious Delicious
Sdílet
Hodnocení (0): 0

Přečtěte si také

Diskuse





Článek zatím nemá žádné komentáře.