本帖最后由 876加几 于 2014-7-30 20:14 编辑
继续演示!!!
Public Module Judge Function Prime(ByVal x As Integer) As Boolean '判断一个数是否是质数 If x < 2 Then Return False Elseif x = 2 Then Return True Else Dim i As Integer For i = 2 To (x - 1) If x Mod i = 0 Then Return False End If End For End If Return True End Function End Module Class Demo Sub New() If Prime(17) Then MsgBox("17是质数") Else MsgBox("17是合数") End If If Prime(16) Then MsgBox("16是质数") Else MsgBox("16是合数") End If '运行结果:17是质数,16是合数 End Sub End Class '以上为VB.NET
Public Module Judge
Function Prime(ByVal x As Integer) As Boolean '判断一个数是否是质数
If x < 2 Then
Return False
Elseif x = 2 Then
Return True
Else
Dim i As Integer
For i = 2 To (x - 1)
If x Mod i = 0 Then
Return False
End If
End For
End If
Return True
End Function
End Module
Class Demo
Sub New()
If Prime(17) Then
MsgBox("17是质数")
Else
MsgBox("17是合数")
End If
If Prime(16) Then
MsgBox("16是质数")
Else
MsgBox("16是合数")
End If
'运行结果:17是质数,16是合数
End Sub
End Class
'以上为VB.NET
def 最大公因数(*num) if num.size = 1 return num[0] elsif num.size = 2 if num[0] % num[1] = 0 return num[1] else return 最大公因数(num[1], num[0] % num[1]) end else num2 = 最大公因数(num[0], num[1]) for i in 2...num.size num2 = 最大公因数(num2, num[i]) end end end p 最大公因数(60, 72, 40) #=>4
def 最大公因数(*num)
if num.size = 1
return num[0]
elsif num.size = 2
if num[0] % num[1] = 0
return num[1]
else
return 最大公因数(num[1], num[0] % num[1])
end
else
num2 = 最大公因数(num[0], num[1])
for i in 2...num.size
num2 = 最大公因数(num2, num[i])
end
end
end
p 最大公因数(60, 72, 40) #=>4
和……以前我写的的求和求积……
def sum(min, max) ary = [] for i in min..max ary.push(yield(i)) end num = 0 for n in ary num += n end return num.truncate == num ? num.truncate : num rescue Nan end def multi(min, max) ary = [] for i in min..max ary.push(yield(i)) end num = ary[0] ary.shift for n in ary num *= n end return num.truncate == num ? num.truncate : num rescue Nan end p sum(1, 3) {i * 3} #=>18 p sum(0, 4) {i / 2.0} #=>3(舍0) p multi(1, 3) {i * 2} #=>48
def sum(min, max)
ary = []
for i in min..max
ary.push(yield(i))
end
num = 0
for n in ary
num += n
end
return num.truncate == num ? num.truncate : num rescue Nan
end
def multi(min, max)
ary = []
for i in min..max
ary.push(yield(i))
end
num = ary[0]
ary.shift
for n in ary
num *= n
end
return num.truncate == num ? num.truncate : num rescue Nan
end
p sum(1, 3) {i * 3} #=>18
p sum(0, 4) {i / 2.0} #=>3(舍0)
p multi(1, 3) {i * 2} #=>48
|