rpct.net
当前位置:首页 >> 请问在VB中,怎么编程求出50以内的素数 >>

请问在VB中,怎么编程求出50以内的素数

编写一个判断素数的函数:function prime(x as long) as boolean dim i as long for i=2 to x-1 if x mod i=0 then prime=false exit function end if next i prime=true end function主程序循环2~50,依次调用上面的函数prime判断是否素数,代码如下:sub main() dim i& for i=2 to 50 if prime(i) then print i end if next i end sub

dim i as integer,tem_tem as integer,tem_i as integer,tem_sum as integerfor i = 1 to 50 step 1 '随机生成五十个数 tem_tem =900*rnd+100 for tem_i = 2 to tem_tem/2+1 step 1 doevents if tem_tem mod tem_i =0 then tem_sum =tem_sum +1 debug.print tem_tem '打印五十个数中的素数. end if next tem_inext i这类题太简单的了,如果不是因为想要财富值的话,我都懒得打了.

Private Sub Command1_Click() Dim i As Integer Dim j As Integer Dim a(100) As Integer Dim k As Integer k = 0 For i = 50 To 150 For j = 1 To i If i Mod j = 0 Then x = x + 1 End If Next If x = 2 Then a(k) = i Text1.Text = Text1.Text & a(k) & "/" k = k + 1 Else x = 0 End If Next End Sub

可根据初等数论的思路,一个整数,若不能整除它的平方根之内的整数,则为素数,如下#include #include main(){ int n,j,sum=0; for(n=2;nfor(j=2;jif((n%j)==0) break; } if(j>sqrt(n)-1){ printf("%d, ",n); sum=sum+1; } } printf("\nsum=%d\n",sum); }

Private Sub command1_Click()a = ""For n = 1 To 50 Step 2 '步长为2,因为偶数肯定不是素数s = 0 '素数标志,0为素数,1为合数For i = 2 To Int(Sqr(n)) '判断一个数是否为素数只要2到这个数的平方根之间的数与它没有能整除的数,它就是素数.If n Mod i = 0 Then 'mod取余,看看是否能整除s = 1 '有能整除的数s置1Exit For '退出当前循环End IfNextIf s = 0 Then a = a & Str(n) & vbCrLf '是素数,加入字符aNextPrint a '打印素数串End Sub

很久没玩VB了,试下 Private Sub Form_Click() For i = 50 To 100 For j = 2 To i \ 2 If i Mod j = 0 Then Exit For ElseIf j = i \ 2 And i Mod j 0 Then Print i; End If Next Next End Sub

这完全是根据数学中关于素数的概念,进行代码编写!利用计算机的高速度解决烦琐的计算.素数:只能被自身和1整除的自然数,叫做素数,1不是素数,2是最小的素数.也就是说,要判断一个自然数n,是否素数,最基本的思路.就是用2,3,

Private Sub Form_Click() Me.Cls Dim i, j, k As Integer For i = 2 To 100 k = 0 For j = 2 To i If i Mod j = 0 Then k = k + 1 Next j If k = 1 Then Print i Next i End Sub

代码如下:Private Sub Form_Click() Dim sum As Integer, i As Integer Print "150的素数有:" For i = 2 To 50 If S(i) = True Then Print i; sum = sum + i End If Next i Print Print "素数之和为:" & sumEnd SubFunction S(n As Integer) As BooleanS = TrueFor i = 2 To Sqr(n) If n Mod i = 0 Then S = False Exit For End IfNext iEnd Function

Module Module1 Sub Main() ListPrimeNumber(500) End Sub'输出[2~m之间的全部素数] Public Sub ListPrimeNumber(ByVal num As Integer) Dim i As Integer For i = 2 To num If IsPrimeNumber(i) = True Then Console.WriteLine(i) End If Next End

网站首页 | 网站地图
All rights reserved Powered by www.rpct.net
copyright ©right 2010-2021。
内容来自网络,如有侵犯请联系客服。zhit325@qq.com