## ProblemYou want to study a sample of Visual Basic's ability to define recursive functions, or you need a factorial function for smaller integers. ## SolutionSample code folder: Chapter 06\Factorial Create a ## DiscussionThe code in this recipe does not represent the most efficient way to calculate factorials for larger integers. You'll want to use a standard The factorial of a number N is the product of all numbers from 1 to N. For example, the factorial of 3 is calculated as 3 x 2 x 1, which results in a value of 6. The Public Function Factorial(ByVal number As Decimal) As Decimal Select Case number Case Is < 0 Throw New Exception("Factorial: Bad argument") Case Is = 0 Return 1 Case Else Return number * Factorial(number - 1) End Select End Function Calling the The following lines demonstrate the Dim result As New System.Text.StringBuilder Dim number As Decimal = 7 result.AppendLine("Factorial(" & number & ")… ") result.AppendLine() result.Append(Factorial(number)) MsgBox(result.ToString()) Figure 6-23 shows the results of calculating the factorial of 7. ## Figure 6-23. Calculating the factorial of a number with the Factorial( ) function## See AlsoSearch for "Factorial" on the Web to learn more about factorials (see, for example, http://mathworld.wolfram.com/Factorial.html). |

Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

ISBN: 0596101775

EAN: 2147483647

EAN: 2147483647

Year: 2006

Pages: 400

Pages: 400

Authors: Tim Patrick, John Craig

Similar book on Amazon

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net