How to generate an N-digit integer random number in VB.NET

1 Answer

0 votes
Imports System

Module Program
    Function GenerateNDigitNumber(n As Integer) As Long
        If n < 1 Then
            Throw New ArgumentException("n must be a positive integer (>= 1).")
        End If
		
		Dim rnd As New Random()

        Dim lowerBound As Long = If(n > 1, CLng(Math.Pow(10, n - 1)), 0)
        Dim upperBound As Long = CLng(Math.Pow(10, n)) - 1

        Dim range As Long = upperBound - lowerBound + 1

        ' Random.NextDouble gives [0.0, 1.0), scale to range
        Dim r As Long = CLng(rnd.NextDouble() * range) + lowerBound

        Return r
    End Function

    Sub Main()
        Console.WriteLine(GenerateNDigitNumber(1))
        Console.WriteLine(GenerateNDigitNumber(4))
        Console.WriteLine(GenerateNDigitNumber(10))
    End Sub
End Module



' run:
'
' 2
' 2507
' 1999131444
'




answered 1 day ago by avibootz
...