How do I use n! in VB? (eg 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720)
Cheers!
Printable View
How do I use n! in VB? (eg 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720)
Cheers!
manual multiplication :rolleyes:
Code:r=1
For x=2 to n
r=r*x
next x
I think that a For ... Next block in a function is the only way.
If there's an easier way, I would like to see it too.Code:Public Function Factorial(n as integer) 'the data type you want
factorial=1
for a=2 to n
factorial=factorial*a
next a
End Function
Quote:
Originally posted by Good Dreams
If there's an easier way, I would like to see it too.
yep there is, just sorted it
Function Factorial(N As Integer)
Factorial = 1
For X = 2 To N
Factorial = Factorial * X
Next X
End Function
Thanks!
Note: 500th post!!!!!
Note: Simone learns :p
btw the inline solution is more efficient
:rolleyes:Quote:
Originally posted by chenko
Note: 500th post!!!!!
defined recursively its like this:
Code:function Fact (x) as long
if x=0 then
Fact = 1
else
Fact = x * Fact(x-1)
end if
end function
The dynamic programming algorithm is much more efficient in this case though, could save you a lot of function calls.
The only problem with using a long datatype is that it will only go up to 12! before it overflows. I'd suggest a double datatype, if you can sacrifice a little accuracy. If you need the range as well as the accuracy, then you could use a string implementation of a number of unlimited accuracy (well unless you run out of memory).
A whole load of notes you have there :DQuote:
Originally posted by kedaman
Note: Simone learns :p