下面是一个VB代码求100~200之间的全部素数的代码:
Public Function IsSushu(ByVal pa As Integer) As Boolean
Dim pb As Integer = pa - 1
Dim res As Boolean = True
For i = 2 To pb
If pa Mod i = 0 Then
res = False
Exit For
End If
Next i
Return res
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = ""
For i = 100 To 200
If IsSushu(i) Then
str = str & i & " "
End If
Next
MsgBox(str)
End Sub
运行结果:
楼主 参考
经常遇到类似的题目,可以参考此程序!
VB 2008 调试通过!
Public Class Form1
Dim prime(100) As Integer
Dim CurrentIndex As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.ScrollBars = ScrollBars.Vertical
CurrentIndex = 1
prime(CurrentIndex) = 2
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim sum As Integer
For i = 3 To 200 Step 2 '显然,单数才有可能是素数
If IsPrime(i) Then
CurrentIndex = CurrentIndex + 1
prime(CurrentIndex) = i
End If
Next
sum = 0
For i = 1 To CurrentIndex '输出到 textbox 框中,一行一个数,并 累计 求和,结果也 输出 在 此框!
TextBox1.Text = TextBox1.Text & i & ", " & prime(i) & vbCrLf
sum = sum + prime(i)
Next
TextBox1.Text = TextBox1.Text & vbCrLf & "sum, " & sum & vbCrLf
End Sub
Private Function IsPrime(ByVal number As Integer) As Boolean '自定义函数,判断是否为素数
Dim i As Integer
IsPrime = True
For i = 1 To CurrentIndex
If number Mod prime(i) Then '用这个数除以自知 的 素数,能整除的显然不是 素数
Else
IsPrime = False
Exit Function
End If
Next
End Function
End Class
#include
#include
void main()
{
int n,i,flag;
for(n=100;n<=200;n++)
{
flag=1;
for(i=2;i<=sqrt(n);i++)//sqrt(j):j开根号。
if(n%i==0)
flag=0;
if(flag==1)
printf("%4d\n",n);
}
}
$a=array();
for($i=100;$i<200;$i++){
if($i%2!=0&&$i%3!=0){
array_push($a,$i);
}
}
foreach($a as $k=>$v){
if($k%10==9){
$v=$v."
";
}
echo $v." ";
}
echo "
100-200之间的以内素数的个数是". count($a);
?>
suanbei