Calculating the factorial of n is very simple. I wrote this program for permutations and combinations: I wanted a rough idea of how many possible answers there would be, so I wrote an n! function to compute the factorial value. A factorial is 123…..n. In a permutation of 5 items, the result is at most 5432*1, which means there are at most 120 possible answers.
Below, I’ve made n! into a Function, with a VB version and a C++ version. People who are just starting to learn loops can use this function to practice how loops work. Also, because I was worried that an integer wouldn’t be able to hold the result, I used a string to return the value. When you use this Function, you need to convert the return value to a numeric type first.
VB Version of the n! Function
Function n_factorial(ByVal n As Integer) As String
Dim temp As UInteger = 1
For x = 1 To n
temp *= x
Next
n_factorial = Str(temp)
End FunctionProject file download (VS2010): Xun6 | 4Shared | Box.net
C++ Version of the n! Function
int n_factorial(int n){
int temp=1,x=1;
for(x=1;x<=n;x++){
temp*=x;
}
return temp;
}Project file download (by code::blocks): Xun6 | 4Shared | Box.net
