Factorial Function in .NET

Heres your chance to share your own tutorials with the community. Just post them on here. If your lucky they may even be posted on the main site.
2 posts Page 1 of 1
Contributors
User avatar
visualtech
VIP - Donator
VIP - Donator
Posts: 265
Joined: Sat Nov 19, 2011 2:19 pm

Factorial Function in .NET
visualtech
In this tutorial, we will look at the Factorial function (x!).

So let's begin by knowing what Factorial really is; Factorial of any number is the product of all positive integers less than or equal to the number.

Now lets take an example: suppose we want to take the factorial of the number 4, this is how we do it.
  • Step 1: Write down all the numbers before 4 (excluding 0) and then multiply them all.
  • Step 2: We get the following 4 x 3 x 2 x 1 which is equal to 24
  • Step 3: So 4! = 24
Well, all this is very easy to do on Pen and Paper[/p] but with VB.NET (or C#) it gets a little tricky.

The basic idea behind the program is to loop the multiplication until the limit is reached (in this case, the number)

That's a lot of talking, now lets write some code....

So open up Visual Studio/Basic and create a new console application project.

Now write the following code between
Code: Select all
Sub Main()
Code: Select all
Dim calc_n_fact As Integer = 0 'Define the Variable in Which We will Store the Values.
Console.Write("Please Enter the Number: " )
Dim n As Integer = Integer.Parse(Console.ReadLine) 'Get the Integer from the User.

For i As Integer = 1 To n 'Loop until the value of i = n , i = 1, i = 2, i = 3 and so on...

calc_n_fact = calc_n_fact * i  ' Initiate the Sequence: 1 * i {1, 2, 3...} {TIP: Can be also written as calc_n_fact *= i}

Next

Console.WriteLine("The Factorial for the Number is: " & calc_n_fact.ToString)) 'Write the Result
Console.ReadLine()

    
So, this is how we gat the factorial of a number in .NET! If you want any other maths functions, don't hesitate to PM me!

+REP if you liked the tutorial.
Image
User avatar
smashapps
Coding Guru
Coding Guru
Posts: 961
Joined: Tue Apr 05, 2011 8:41 am

Re: Factorial Function in .NET
smashapps
This is a useful tutorial, we written +rep well done
My name is Tom | Visit my blog where I post new content every day! Tom's Daily Blog | MineCraft is awesome!
2 posts Page 1 of 1
Return to “Tutorials”