Как вычислить факториал в c
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
Recursive Solution:
Factorial can be calculated using following recursive formula.
Following is implementation of factorial.
Time Complexity: O(n)
Auxiliary Space: O(n)
Iterative Solution:
Factorial can also be calculated iteratively as recursion can be costly for large numbers. Here we have shown the iterative approach using both for and while loop.
Using For loop
Output:
Time Complexity: O(n)
Auxiliary Space: O(1)
Using While loop
Output:
Time Complexity: O(n)
Auxiliary Space: O(1)
One line Solution (Using Ternary operator):
Как вычислить факториал на c#?
Каким самым простым способом в c# можно вычислить факториал.
C# мультипарадигменный язык, поэтому в нём может быть несколько простых способов вычисления факториала.
Императивный способ это классический цикл for :
Здесь мы использовали тип BigInteger , который позволяет вычислять факториалы произвольного размера.
Рекурсивный способ здесь в ответах уже привели.
Можно привести другой функциональный способ вычисления, основанный на возможностях LINQ:
Как вычислить факториал в c
Отдельно остановимся на рекурсивных функциях. Рекурсивная функция представляет такую конструкцию, при которой функция вызывает саму себя.
Рекурсивная функция факториала
Возьмем, к примеру, вычисление факториала, которое использует формулу n! = 1 * 2 * … * n . То есть по сути для нахождения факториала числа мы перемножаем все числа до этого числа. Например, факториал числа 4 равен 24 = 1 * 2 * 3 * 4 , а факторил числа 5 равен 120 = 1 * 2 * 3 * 4 * 5 .
Определим метод для нахождения факториала:
При создании рекурсивной функции в ней обязательно должен быть некоторый базовый вариант , с которого начинается вычисление функции. В случае с факториалом это факториал числа 1, который равен 1. Факториалы всех остальных положительных чисел будет начинаться с вычисления факториала числа 1, который равен 1.
На уровне языка программирования для возвращения базового варианта применяется оператор return :
То есть, если вводимое число равно 1, то возвращается 1
Другая особенность рекурсивных функций: все рекурсивные вызовы должны обращаться к подфункциям, которые в конце концов сходятся к базовому варианту:
Так, при передаче в функцию числа, которое не равно 1, при дальнейших рекурсивных вызовах подфункций в них будет передаваться каждый раз число, меньшее на единицу. И в конце концов мы дойдем до ситуации, когда число будет равно 1, и будет использован базовый вариант. Это так называемый рекурсивный спуск.
Используем эту функцию:
Рассмотрим поэтапно, что будет в случае вызова Factorial(4) .
Сначала идет проверка, равно ли число единице:
Но вначале n равно 4, поэтому это условие ложно, и соответственно выполняется код
То есть фактически мы имеем:
Далее выполняется выражение:
Опять же n не равно 1, поэтому выполняется код
То есть фактически:
Далее выполняется выражение:
Опять же n не равно 1, поэтому выполняется код
То есть фактически:
Далее выполняется выражение:
Теперь n равно 1, поэтому выполняется код
И возвращается 1.
В итоге выражение
В реальности выливается в
Рекурсивная функция Фибоначчи
Другим распространенным показательным примером рекурсивной функции служит функция, вычисляющая числа Фибоначчи. n-й член последовательности Фибоначчи определяется по формуле: f(n)=f(n-1) + f(n-2), причем f(0)=0, а f(1)=1. То есть последовательность Фибоначчи будет выглядеть так 0 (0-й член), 1 (1-й член), 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, . Для определения чисел этой последовательности определим следующий метод:
Здесь базовый вариант выглядит следующий образом:
То есть, если мы ищем нулевой или первый элемент последовательности, то возвращается это же число — 0 или 1. Иначе возвращается результат выражения Fibonachi(n — 1) + Fibonachi(n — 2);
Рекурсии и циклы
Это простейшие пример рекурсивных функций, которые призваны дать понимание работы рекурсии. В то же время для обоих функций вместо рекурсий можно использовать циклические конструкции. И, как правило, альтернативы на основе циклов работают быстрее и более эффективны, чем рекурсия. Например, вычисление чисел Фибоначчи с помощью циклов:
В то же время в некоторых ситуациях рекурсия предоставляет элегантное решение, например, при обходе различных древовидных представлений, к примеру, дерева каталогов и файлов.
Factorial in C
By
Swati Tawde

Introduction to Factorial in C program
The following article, Factorial in C Program, provides an outline for C’s topmost factorial methods. The symbol for factorial is denoted by using this! ‘ sign. For instance, the number 6 factorial is referred to as 6!. Number factorial is described as the product “of the number, and all the entries are smaller than zero and negative.” For factorial concepts, natural numbers (non-negative entities) higher than zero are used.
Let us see some examples to understand how factorial is calculated. Below we have calculated factorial for numbers 1 to 10.
Web development, programming languages, Software testing & others
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
- Factorial of ZERO (0!) = 1
- Factorial of one (1!) = 1
- Factorial of Two (2!) = 2*1 = 2
- Factorial of Three (3!) = 3*2*1 = 6
- Factorial of Four (4!) = 4*3*2*1 = 24
- Factorial of Five (5!) = 5*4*3*2*1 = 120
- Factorial of Six (6!) = 6*5*4*3*2*1 = 720
- Factorial of seven (7!) = 7*6*5*4*3*2*1 = 5040
- Factorial of Eight (8!) = 8*7*6*5*4*3*2*1 = 40320
- Factorial of nine (9!) = 9*8*7*6*5*4*3*2*1 = 362880
- Factorial of Ten (10!) = 10*9*8*7*6*5*4*3*2*1 = 3628800
Below is the common mathematical formula for determining the numbers ‘ n ‘ factor.
n! = n ( n – 1)( n – 2)( n – 3) ……
Examples of Factorial in C by Using various method
In this section, we are going to discuss how factorial is calculated in the C program using different methods.
Example #1 – Using the if-else statement
If the statement is evaluated in an if-else statement, if the statement in it is true, it will give the output. If the statement in if the condition is not true, it transfers the control to the else statement and else statement is being executed. Let us see how we can calculate factorial using the if-else statement.
Code
Explanation of the above code
In the above example, we have initialized three variables number, i.e. I and fact. Then scan function is used to allow a user to enter the number by their wish. If the condition first checks if the given number is negative or not, if it is negative, it will execute if the statement and throw the error and stop the program.
Output for the negative number:

And if the given number is positive, it will transfer control to else statement and condition are given in the else statement is executed, and it will calculate the factorial for a given number. The output for the positive number is as follows.
Output for the positive number:

Example #2 – Using For loop
In the For loop, the first initialization step is executed and only once in the whole program. In this step, you can initialize and declare variables for the code. After that condition is evaluated. If the condition is true, then it will execute the code inside the block of For loop. If the condition is false, it will jump to the code after the For loop without executing the For loop code.
After the For loop, the increment statement will be executed. After that, again, the condition will be checked. Loop will get executed if the condition is true, and the loop will repeat itself, i.e. the body of the loop, an increment statement, and condition. The loop ends when the condition is false.
Code
Output:

Explanation of the above program
In this program, we have initialized the variables I, fact and number. When the condition of for loop. The scan function is used to allow a user to enter the number by their wish. After that, For loop will work as explained above.
Example #3 – Using recursion method
Recursion is a method where, for instance, the feature itself is called in the software factory function below. You first need to convey its answer in the recursive form to resolve an issue via resource.
Code
Output:
![]()
Example #4 – Using function
Output:

Conclusion
In this article, we have seen how to calculate the factorial of a number in C by using conditional statements and functions. I hope this article will help you in understanding the working of factorial in C.
Recommended Articles
This has been a guide to Factorial in C. Here we discuss factorial for numbers 1 to 10, examples of factorial in C by using the various method, formula for “n factor” with codes and outputs. You can also go through our given articles to learn more-