Факториал числа си шарп

Факториал числа си шарп

Отдельно остановимся на рекурсивных функциях. Рекурсивная функция представляет такую конструкцию, при которой функция вызывает саму себя.

Рекурсивная функция факториала

Возьмем, к примеру, вычисление факториала, которое использует формулу 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, и будет использован базовый вариант. Это так называемый рекурсивный спуск.

int Factorial(int n) < if (n == 1) return 1; return n * Factorial(n - 1); >int factorial4 = Factorial(4); // 24 int factorial5 = Factorial(5); // 120 int factorial6 = Factorial(6); // 720 Console.WriteLine($"Факториал числа 4 = "); Console.WriteLine($"Факториал числа 5 = "); Console.WriteLine($"Факториал числа 6 = ");

Рассмотрим поэтапно, что будет в случае вызова Factorial(4) .

    Сначала идет проверка, равно ли число единице:

В реальности выливается в

Рекурсивная функция Фибоначчи

Другим распространенным показательным примером рекурсивной функции служит функция, вычисляющая числа Фибоначчи. 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, . Для определения чисел этой последовательности определим следующий метод:

int Fibonachi(int n) < if (n == 0 || n == 1) return n; return Fibonachi(n - 1) + Fibonachi(n - 2); >int fib4 = Fibonachi(4); int fib5 = Fibonachi(5); int fib6 = Fibonachi(6); Console.WriteLine($"4 число Фибоначчи = "); Console.WriteLine($"5 число Фибоначчи = "); Console.WriteLine($"6 число Фибоначчи = ");

Здесь базовый вариант выглядит следующий образом:

То есть, если мы ищем нулевой или первый элемент последовательности, то возвращается это же число — 0 или 1. Иначе возвращается результат выражения Fibonachi(n — 1) + Fibonachi(n — 2);

Рекурсии и циклы

Это простейшие пример рекурсивных функций, которые призваны дать понимание работы рекурсии. В то же время для обоих функций вместо рекурсий можно использовать циклические конструкции. И, как правило, альтернативы на основе циклов работают быстрее и более эффективны, чем рекурсия. Например, вычисление чисел Фибоначчи с помощью циклов:

static int Fibonachi2(int n) < int result = 0; int b = 1; int tmp; for (int i = 0; i < n; i++) < tmp = result; result = b; b += tmp; >return result; >

В то же время в некоторых ситуациях рекурсия предоставляет элегантное решение, например, при обходе различных древовидных представлений, к примеру, дерева каталогов и файлов.

Источник

Factorial Number Program in C#

Factorial Number Program in C# with Examples

  1. What is factorial of a number?
  2. Factorial of a number using for loop, while loop and do-while loop in C#.
  3. Factorial of a number using the recursive function in C#.
What is Factorial of a number?

The Factorial of a number (let say n) is nothing but the product of all positive descending integers of that number. Factorial of n is denoted by n!. Please have a look at the following image which shows how to calculate the factorials of a number.

Factorial Program in C# with Examples

Factorial Number Program in C# using for loop:

In the following example, we take the number from the console and then calculate the factorial of that number using for loop.

using System; namespace LogicalPrograms < class Program < static void Main(string[] args) < Console.Write("Enter a Number : "); int number = int.Parse(Console.ReadLine()); int factorial = 1; for (int i = 1; i Console.Write($"Factorial of is: "); Console.ReadLine(); > > >
Output:

Factorial Number Program in C# using for loop

Factorials of a number using while loop in C#:

In the following example, we use while loop to calculate the factorial of a number.

using System; namespace LogicalPrograms < class Program < static void Main(string[] args) < Console.Write("Enter a Number : "); int number = int.Parse(Console.ReadLine()); long factorial = 1; while (number != 1) < factorial = factorial * number; number = number - 1; >Console.Write($"Factorial is: "); Console.ReadLine(); > > >
Output:

Factorials of a number using while loop in C#

Factorial of a number using Recursive Function in C#:

In the following program, we use a recursive function to calculate the factorial of a given number.

using System; namespace LogicalPrograms < class Program < static void Main(string[] args) < Console.Write("Enter a Number : "); int number = int.Parse(Console.ReadLine()); long factorial = RecursiveFactorial(number); Console.Write($"Factorial of is: "); Console.ReadLine(); > static long RecursiveFactorial(int number) < if (number == 1) < return 1; >else < return number * RecursiveFactorial(number - 1); >> > >
Output:

Factorial of a number using Recursive Function in C#

Factorial of a number using the do-while loop in C#:

In the below program, we use the do-while loop to calculate the factorial of a given number. The number here we are taking from the console.

using System; namespace LogicalPrograms < class Program < static void Main(string[] args) < Console.Write("Enter a Number : "); int number = int.Parse(Console.ReadLine()); long factorial = 1; do < factorial = factorial * number; number--; >while (number > 0); Console.Write($"The Factorial is: "); Console.ReadLine(); > > >
Output:

Factorial of a number using do while loop in C#

In the next article, I am going to discuss the Sum Of Digits Program in C# with some examples. Here, in this article, I try to explain the different ways to implement the Factorial Number Program in C# with examples.

Источник

Factorial in C#

Factorial in C#

In this section, we shall see the factorial in c# in detail. Factorial is a very important concept in the area of mathematics like in algebra or in mathematics analytics. It is denoted by sign of exclamation (!). Factorial is any positive integer k, which is denoted by k! It is the product of all positive integers which are less than or equal to k.

Web development, programming languages, Software testing & others

Logic to Calculate Factorial of A Given Number

For example, if we want to calculate the factorial of 4 then it would be,

Similarly, by using this technique we can calculate the factorial of any positive integer. The important point here is that the factorial of 0 is 1.

There are many explanations for this like for n! where n=0 signifies product of no numbers and it is equal to the multiplicative entity. >=>=1.>

The factorial function is mostly used to calculate the permutations and combinations and also used in binomial. With the help of the factorial function, we can also calculate the probability. For example in how many ways we can arrange k items. We have k choices for the first thing, So for each of these k choices, we left with k-1 choices for the second things (because first choice has already been made), so that now we have k(k-1) choices, so now for the third choice we have k(k-1)(k-2) choices and so on until we get one on thing is remaining. So altogether we will have k(k-1)(k-2)(k-3)…3..1.

Another real-time example is supposed we are going to a wedding and we want to choose which blazer to take. So let’s suppose we have k blazers and but have room to pack the only n. So how many ways we can use n blazers from a collection of k blazers k!/(n!.(k-n)!).

Examples of Factorial in C#

Below are the examples to show how we can calculate factorial of any number in different ways,

Example #1

1. In these examples, for loop is used to calculate the factorial of a number.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factorial < class Program < static void Main() < int a = 7; int fact = 1; for (int x = 1; x Console.WriteLine(fact); Console.ReadLine(); > > >

In this example, the variable of integer data type is initialized and for loop is used to calculate the number.

2. In this example, the user is allowed to enter the number to calculate the factorial.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactorialExample < class Program < static void Main() < Console.WriteLine("Enter the number: "); int a = int.Parse(Console.ReadLine()); int fact = 1; for (int x = 1; x Console.WriteLine(fact); Console.ReadLine(); > > >

Factorial in C# 1-2

Example #2

1. In these examples, for loop is used to calculate the factorial of a number.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factorial < class Program < static void Main() < int a = 10; int fact = 1; while (true) < Console.Write(a); if (a == 1) < break; >Console.Write("*"); fact *= a; a--; > Console.WriteLine(" = ", fact); Console.ReadLine(); > > >

Factorial in C# 1-3

2. In these examples, while loop is used to calculate the factorial of a number.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactorialExample < class Program < static void Main() < Console.WriteLine("Enter the number: "); int a = int.Parse(Console.ReadLine()); int fact = 1; while(true) < Console.Write(a); if(a==1) < break; >Console.Write("*"); fact *= a; a--; > Console.WriteLine(" = ", fact); Console.ReadLine(); > > >

while loop

Example #3

1. In this example, do-while is used to calculate the factorial of a number.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factorial < class Program < static void Main() < int a = 6; int fact = 1; do < fact *= a; a--; >while (a > 0); Console.WriteLine("Factorial = ", fact); Console.ReadLine(); > > >

 do-while loop

2. In this example, do-while is used to calculate the factorial of a number.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactorialExample < class Program < static void Main() < Console.Write("Enter the number: "); int a = int.Parse(Console.ReadLine()); int fact = 1; do < fact *= a; a--; >while (a > 0); Console.WriteLine("Factorial = ", fact); Console.ReadLine(); > > >

Factorial in C# 1-6

Example #4

1. In this example, a recursive function is used to calculate the factorial of a number.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factorial < class Program < static void Main() < int n= 5; long fact = Fact(n); Console.WriteLine("factorial is ", n, fact); Console.ReadKey(); > private static long Fact(int n) < if (n == 0) < return 1; >return n * Fact(n - 1); > > >

In the above example, the factorial of a number is achieved by using recursion. The idea behind the recursion is to solve the problem in small instances. So whenever a function creating a loop and calling itself, it’s called recursion.

Factorial in C# 1-7

2. In this example, a recursive function is used to calculate the factorial of a number.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactorialExample < class Program < static void Main() < Console.WriteLine("Enter the number"); int n = Convert.ToInt32(Console.ReadLine()); long fact = Fact(n); Console.WriteLine("factorial is ", n, fact); Console.ReadKey(); > private static long Fact(int n) < if (n == 0) < return 1; >return n * Fact(n - 1); > > >

Factorial in C# 1-8

Conclusion

So the concept of factorial is very important in areas of mathematics such as binomials and permutations and combinations, and this is how we can print the factorial of any number by using multiple methods such as for, while, do-while, function, etc.

This is a guide to Factorial in C#. Here we discuss the basic concept of factorial in c# along with different examples and code implementation. You may also look at the following articles to learn more –

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

C# Course Bundle — 24 Courses in 1 | 5 Mock Tests
111+ Hours of HD Videos
24 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.6

Источник

Csharp Star

Tutorials, Tips and Tricks on Microsoft Technologies !!

3 Different ways to calculate factorial in C#

In this article, we will discuss different ways for calculating factorial in C#.

Calculate Factorial

Factorial of a number is obtained from the result of multiplying a series of descending natural numbers.

This C# Program generates Factorial of the Number obtained from the user.

1. Using For Loop:

/* * C# Program to Generate the Factorial of Given Number */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace factorial < class Program < static void Main(string[] args) < int i, number, fact; Console.WriteLine("Enter the Number"); number = int.Parse(Console.ReadLine()); fact = number; for (i = number - 1; i >= 1; i--) < fact = fact * i; >Console.WriteLine("\nFactorial of Given Number is: "+fact); Console.ReadLine(); > > >

Here is the output of the C# Program:

Enter the Number
5
Factorial of Given Number is: 120

You can calculate factorial using recursion and while loop also.

2. Using Recursion:

public double factorial_Recursion(int number)

3. Using While loop:

public double factorial_WhileLoop(int number) < double result = 1; while (number != 1) < result = result * number; number = number - 1; >return result; >

© 2016, Csharp Star. All rights reserved.

Share this:

Источник

Читайте также:  Файл access php битрикс
Оцените статью