九、
埃及分数:
古埃及人有一个非常奇特的习惯,他们喜欢把一个分数表示为若干个分子为
1
,分母不同的分数的和的形式。例如:
7/8=1/2+1/3+1/24
答:
源程序:
Private Sub Command1_Click()
Dim a As Long, b As Long, i As Long
Dim g As Long, t As Long
Dim s As String
s = ""
i = 2
a = Int(Trim(Text1.Text))
b = Int(Trim(Text2.Text))
t = gcd(a, b)
a = a \ t
b = b \ t
Do
If a > b Then
s = s & "1/1+"
a = a - b
Else
If a / b >= 1 / i Then
g = i * b \ gcd(i, b)
a = a * (g \ b) - g \ i
b = g
t = gcd(a, b)
a = a \ t
b = b \ t
s = s & "1/" & i & "+"
If a = 1 Then
s = s & "1/" & b
Exit Do
End If
End If
i = i + 1
End If
Loop Until (a = 0)
If Right(s, 1) = "+" Then s = Left(s, Len(s) - 1)
Text3 = s
End Sub
Private Function gcd(ByVal x As Long, ByVal y As Long) As Long
Dim t As Long
Do
t = x Mod y
x = y
y = t
Loop Until (t = 0)
gcd = x
End Function
Private Sub Command2_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text1.SetFocus
End Sub
Private Sub Command3_Click()
End
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
Text2.SetFocus
End If
End Sub
十、用1—9这9个数组成三个三位的平方数,要求每个数字只准使用一次。
答:
源程序:
Private Sub Command1_Click()
Dim i As Integer, j As Integer, k As Integer, t As Integer
Dim a() As Integer, b(1 To 9) As Integer
Dim s As String
For i = 1 To 9
b(i) = i
Next i
l = 0
s = ""
For i = 1 To 9
b(i) = i
Next i
For i = 1 To 9
For j = 1 To 9
For k = 1 To 9
If i <> j And i <> k And j <> k Then
t = b(i) * 100 + b(j) * 10 + b(k)
If pfs(t) And Len(CStr(t)) = 3 And Right(CStr(t), 1) <> "0" Then
l = l + 1
ReDim Preserve a(l)
a(l) = t
End If
End If
Next k
Next j
Next i
For i = 1 To UBound(a) - 2
For j = i + 1 To UBound(a) - 2
For k = j + 1 To UBound(a)
s = a(i) & a(j) & a(k)
If pd(s) = True Then Text1 = a(i) & " " & a(j) & " " & a(k)
Next k
Next j
Next i
End Sub
Private Function pd(s As String) As Boolean
Dim i As Integer
For i = 1 To Len(s) - 1
For j = i + 1 To Len(s)
If Mid(s, i, 1) = Mid(s, j, 1) Then
pd = False
Exit Function
Else
pd = True
End If
Next j
Next i
End Function
Private Function pfs(t As Integer) As Boolean
If Int(Sqr(t)) ^ 2 = t Then
pfs = True
Else
pfs = False
End If
End Function
posted on 2006-09-29 10:01
木子李 阅读(158)
评论(0) 编辑 收藏 引用 网摘 所属分类:
Visual Basic 课堂