实例006查找随机数组中质数的个数

Visual Basic 中的数组

https://docs.microsoft.com/zh-cn/dotnet/visual-basic/programming-guide/language-features/arrays/#the-array-type

Array 类

https://docs.microsoft.com/zh-cn/dotnet/api/system.array?view=netframework-4.8

VBMath.Randomize 方法

https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.visualbasic.vbmath.randomize?view=netframework-4.8

VBMath.Rnd 方法

https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.visualbasic.vbmath.rnd?view=netframework-4.8#Microsoft_VisualBasic_VBMath_Rnd

Conversion.Int 方法

https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.visualbasic.conversion.int?view=netframework-4.8

NET 中的格式类型

https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/formatting-types

控制台程序

Module Module1

    Sub Main()
        '源数组
        Dim scArray(20) As Integer
        '找到的结果数组
        Dim resPArray(0) As Integer
        'MsgBox(scArray.GetUpperBound(0)),获取数组第一维的最大下标,比元素个数小1
        'MsgBox(scArray.GetLength(0)),获取数组第一维长度
        '循环计数
        Dim icount As Integer
        '保存生成的随机数
        Dim Rnds As Integer
        '随机种子
        Randomize()

        Console.WriteLine("生成21个2到10000间随机数")
        For icount = 0 To 20
            Rnds = Int(Rnd() * 9998 + 2)
            '等价天scArray(icount)=Rnds
            scArray.SetValue(Rnds, icount)
            'scArray.GetValue(icount)等价于scArray(icount)
            Console.Write(Convert.ToString(scArray.GetValue(icount)) & ", ")
        Next
        Console.WriteLine()

        '找质数
        For icount = 0 To 20
            If IsPrimeNumber(scArray.GetValue(icount)) Then
                ReDim Preserve resPArray(resPArray.GetUpperBound(0) + 1)
                resPArray.SetValue(scArray.GetValue(icount), resPArray.GetUpperBound(0))
            End If
        Next

        '结果
        Console.WriteLine("数列中的质数有:{0:###}个", resPArray.GetLength(0) - 1)
        For icount = 1 To resPArray.GetUpperBound(0)
            Console.Write(resPArray.GetValue(icount))
            Console.Write(". ")
        Next

        Console.ReadLine()
    End Sub
    '判断质数
    Public Function IsPrimeNumber(ByVal pNumber As Integer) As Boolean
        Dim iFactor As Integer
        For iFactor = 2 To Int(Math.Sqrt(pNumber))
            If pNumber Mod iFactor = 0 Then
                Return False
            End If
        Next
        Return True
    End Function
End Module
 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ngbshzhn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值