Algorithm - Factorial of an Number in VB.NET

Factorials are very simple, the factorial of any number is that number times the factorial of 1 smaller than that number.
  • 8373


Factorials are very simple things. They're just products, indicated by an exclamation mark. For instance, "four factorial" is written as "4!" and means 1x2x3x4 = 24. the factorial of any number is that number times the factorial of (1 smaller than that number), factorial(N), for scalar N, is the product of all the integers from 1 to N, i.e. prod(1:n). When N is an N-dimensional array, factorial(N) is the factorial for each element of N.

The factorial function can also be defined for non-integer values using more advanced mathematics. This more generalized definition is used by advanced calculators and mathematical software such as Maple or Mathematica.

factorial1.gif

factorial2.gif

Finding Factorial of a given number is another interesting problem. Mathematically represented as n.
For ex:

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

Not to forget that 1! = 1 and 0! = 1.

We can now generalize the factorial of a given number which is any thing other than zero and one as the product of all the numbers ranging from given number to 1.

i.e n! = n * (n - 1) * (n - 2 ) * ...*1

Algorithm : Factorial

Input : n

Output : Factorial of n

Method
    fact = 1
    for i = n to 1 in steps of -1 do
        fact = fact*i
    end_for
    display 'factorial = ',fact

Algorithm ends

In the above algorithm we have implemented the logic of the equation

n! = n * (n - 1) * (n - 2 ) * ... *1.

The same can be achieved by the following algorithm which follows incremental steps rather than decremental steps of the given algorithm.

Algorithm : Factorial

Input : n

Output : Factorial of n

Method
    fact = 1
    for i = 1 to n in steps of 1 do
        fact = fact*i
    end_for
    display 'factorial = ',fact

Algorithm ends
  

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.