Как найти факториал си шарп

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

Императивный способ это классический цикл for:

// подключаем сборку System.Runtime.Numerics для типа BigInteger
using System.Numerics;

public BigInteger Factorial(int n)
{
    var factorial = new BigInteger(1);
    for (int i = 1; i <= n; i++)
        factorial *= i;

    return factorial;
}

Здесь мы использовали тип BigInteger, который позволяет вычислять факториалы произвольного размера.

Рекурсивный способ здесь в ответах уже привели.

Можно привести другой функциональный способ вычисления, основанный на возможностях LINQ:

public BigInteger Factorial(int n)
{
    return Enumerable.Range(1, n)
                     .Aggregate(new BigInteger(1), (f, i) => f * i);
}

По сути здесь делается то же самое, что и в первом примере.

Calculating factorial is a common task in programming. In C#, a factorial can be calculated in several ways, including loops and recursion. In this article, we will explore different ways to calculate factorial in C# and provide full code examples with explanations.

calculate-factorial-in-csharp

Table of Contents

  • 1 What is Factorial in C#?
  • 2 Different Ways to Calculate Factorial in C#:
  • 3 01. Using For Loop: 
  • 4 02. Using Recursion:
    • 4.1 Code Explanation:
  • 5 03. Using While Loop: 
  • 6 04. Using do While Loop: 
  • 7 05. Calculate Factorial in C# Using LINQ:
  • 8 Conclusion:
  • 9 FAQs
    • 9.1 Q: What is the maximum value of n that can be used to calculate factorial in C#?
    • 9.2 Q: Can recursion be used to calculate large factorials in C#?
    • 9.3 Q: Can we use nested loops to calculate factorial in C#?
    • 9.4 Q: What are some practical applications of calculating factorial in C#?
    • 9.5 Related

What is Factorial in C#?

Factorial is a mathematical operation that multiplies a given number by all the positive integers that come before it. In C#, it is commonly used in various programming tasks, such as probability calculations and combinatorial analysis.

In C#, you can calculate the factorial of a number by using a loop that continues until the number is no longer equal to 1.
Simply set the initial value of n to the number for which you want to find the factorial, and then loop through until n is no longer equal to 1.

The following are the different ways to calculate factorial in C#.

01. Using For Loop: 

We can use a for loop to calculate factorial in C#. Here is an example:

using System;
namespace FactorialUsingForLoop
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 5;
            int factorial = 1;
            for (int i = 1; i <= n; i++)
            {
                factorial = factorial * i;
            }
            Console.WriteLine($"Factorial of {n} is {factorial}");
            Console.ReadLine();
        }
    }
}

Output:

02. Using Recursion:

Recursion is another way to calculate factorial in C#. Here is an example:

using System;
namespace FactorialUsingRecursion
{
    class Program
    { 
        // Factorial Using Recursion Method:
        public static int Factorial(int n)
        {
            if (n == 0)
                return 1;
            return n * Factorial(n - 1);
        }
        static void Main(string[] args)
        {
            int n = 5;
            Console.WriteLine("Factorial of {0} is {1}", n, Factorial(n));
            Console.ReadLine();
        }
    }   
}
// Output: Factorial of 5 is 120

Code Explanation:

The above C# code calculates the factorial of a number using a recursive function. The factorial of a number is the product of all the positive integers from 1 to that number.

For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1, which equals 120.
The function Factorial(int n) takes a number as its input and returns its factorial. If the input number is 0, the function returns 1.

Otherwise, it calculates the factorial recursively by calling itself with the argument n-1 and multiplying the result with the original n. This process continues until the input number becomes 0. When the function returns 1, then recursion ends.

03. Using While Loop: 

We can also use a while loop to calculate factorial in C#. Here is an example:

using System;
namespace FactorialUsingWhileLoop
{
    class Program
    { 
        
        static void Main(string[] args)
        {
            int n = 5;
            int factorial = 1;
            int i = 1;
            while (i <= n)
            {
                factorial = factorial * i;
                i++;
            }

            Console.WriteLine($"Factorial of {n} is {factorial}");
            Console.ReadLine();
        }
    }   
}
// Output: Factorial of 5 is 120

04. Using do While Loop: 

do while loop can also be used to calculate factorial in C#. Here is an example:

using System;
namespace FactorialUsingDoWhileLoop
{
    class Program
    { 
        
        static void Main(string[] args)
        {
            int n = 5;
            int factorial = 1;
            int i = 1;
            do
            {
                factorial = factorial * i;
                i++;
            }
            while (i <= n);
            Console.WriteLine($"Factorial of {n} is {factorial}");

            Console.ReadLine();
        }
    }   
}
// Output: Factorial of 5 is 120

05. Calculate Factorial in C# Using LINQ:

C# provides a powerful feature called Language-Integrated Query (LINQ) which allows us to perform complex queries on data. We can use LINQ to calculate factorial as follows:

using System;
using System.Linq;
namespace FactorialUsingLINQ
{
    class Program
    {       
        static void Main(string[] args)
        {
            int n = 5;
            int factorial = Enumerable.Range(1, n).Aggregate((x, y) => x * y);
            Console.WriteLine("Factorial of {0} is: {1}", n, factorial);

            Console.ReadLine();
        }
    }   
}
//Output: Factorial of 5 is: 120

In the code above, we first create a range of numbers from 1 to n using the Enumerable.Range method. We then use the Aggregate method to multiply all the numbers in the range together, resulting in the factorial value.

Conclusion:

In conclusion, calculating factorial in C# can be done in several ways, including loops and recursion. Each method has its advantages and disadvantages, and the choice of method depends on the specific requirements of the task. It is important to choose the right method to optimize performance and accuracy.

FAQs

Q: What is the maximum value of n that can be used to calculate factorial in C#?

The maximum value of n that can be used to calculate factorial in C# depends on the data type used to store the result. For example, if an int data type is used, the maximum value of n is 12. If a long data type is used, the maximum value of n is 20.

Q: Can recursion be used to calculate large factorials in C#?

Recursion can be used to calculate large factorials in C#, but it may not be the most efficient method for large values of n.

Q: Can we use nested loops to calculate factorial in C#?

Yes, Nested loops can be used to calculate factorial in C#. However, it may not be the most efficient method for large values of n and can result in slower execution time.

Q: What are some practical applications of calculating factorial in C#?

Factorial can be used in various programming tasks, such as probability calculations, combinatorial analysis, and cryptography. For example, a factorial can be used to calculate the number of permutations and combinations of a set of objects.

Articles you might also like:

  • Design Patterns
  • Builder Design Pattern: A Comprehensive Guide with C# Code Examples
  • SOLID Design Principles in C#: A Complete Example
  • Singleton Design Pattern in C#: A Beginner’s Guide with Examples
  • Abstract Factory Design Pattern in C#
  • Author
  • Recent Posts

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g

Meet Shekh Ali, a skilled Software engineer and passionate blogger with an MCA degree and 8+ years of experience in the field. He enjoys sharing his expertise in C#, Java, SQL, Design Patterns, and other related topics through his writing. When he’s not coding, Shekh Ali can often indulge in his passions for reading books and fitness training.

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g

Back to: C#.NET Programs and Algorithms

Factorial Number Program in C# with Examples

In this article, I am going to discuss the Factorial Number Program in C# with Examples. Please read our previous article where we discussed the Armstrong Number Program in C# with examples. In many interviews, the interviewer asked this question in many different ways. As part of this article, we are going to discuss the following pointers.

  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 <= number; i++)
            {
                factorial = factorial * i;
            }
            Console.Write($"Factorial of {number}  is: {factorial}");
            
            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: {factorial}");           
            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 {number} is: {factorial}");    
            
            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: {factorial}");
            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#

Introduction to 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.

k!= k * (k-1) *(k-2) *(k-3) *(k-4) *…….3 *2 * 1.

Logic to Calculate Factorial of A Given Number

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

Example #1

4! = 4 * (4-1) *(4-2) * (4-3)

4! = 4 * 3 * 2 * 1

4! = 24.

So factorial of 4 is 24

Example #2

6! = 6 * (6-1)* (6-2)* (6-3) * 6-4)* (6-5)

6! = 6*5*4*3*2*1

6! = 720

So factorial of 6 is 720

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.

0! =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. {displaystyle {binom {0}{0}}={frac {0!}{0!0!}}=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.

Code:

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 <= a; x++)
{
fact *= 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.

Output:

integer data type

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

Code:

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 <= a; x++)
{
fact *= x;
}
Console.WriteLine(fact);
Console.ReadLine();
}
}
}

Output:

Factorial in C# 1-2

Example #2

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

Code:

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(" = {0}", fact);
Console.ReadLine();
}
}
}

Output:

Factorial in C# 1-3

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

Code:

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(" = {0}", fact);
Console.ReadLine();
}
}
}

Output:

while loop

Example #3

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

Code:

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 = {0}", fact);
Console.ReadLine();
}
}
}

Output:

 do-while loop

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

Code:

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 = {0}", fact);
Console.ReadLine();
}
}
}

Output:

Factorial in C# 1-6

Example #4

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

Code:

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 {1}", 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.

Output:

Factorial in C# 1-7

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

Code:

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 {1}", n, fact);
Console.ReadKey();
}
private static long Fact(int n)
{
if (n == 0)
{
return 1;
}
return n * Fact(n - 1);
}
}
}

Output:

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.

Recommended Articles

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 –

  1. Virtual Keyword in C# 
  2. TextWriter in C#
  3. C# SortedSet
  4. C# finally

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)
{
    if (number == 1)
        return 1;
    else
        return number * factorial_recursion(number - 1);
}

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.

Понравилась статья? Поделить с друзьями:
  • Как составить рассказ по рисунку лягушка путешественница
  • Найди сериал мыслить как преступник
  • Как найти полное давление жидкости
  • Как найти клиентов для продаж сайтов
  • Щенок косолапит передними лапами как исправить