VB中求最大公约数最小公倍数

VB中求最大公约数最小公倍数,第1张

r没有初值,程序开始后
Do Until r = 0
m1 = n1
n1 = r
r = m1 - n1
Loop
这一段没什么用。。。直接就r=0了

Private Sub Command1_Click()
Dim a As Long, b As Long

a = Val(InputBox("输入一个数a:"))
b = Val(InputBox("输入一个数b:"))
For i = 1 To sMin(a, b)
If (a / i = a \ i) And (b / i = b \ i) Then c = i
Next
Print "最大公约数是:"; c

End Sub
Function sMin(a As Long, b As Long) As Long
If a < b Then
sMin = a
Else
sMin = b
End If
End Function

Private Sub Command1_Click()
   Dim a()
   Dim b, c, gys
   Dim n As Integer
   Cls
   n = Val(InputBox("请你输入要输入的个数!"))
   ReDim a(1 To n)
   For i = 1 To n
      a(i) = Val(InputBox("请输入第" & i & "个数"))
      Print a(i)
   Next i
   c = a(1)
   b = a(1)
   For i = 2 To n
      b = a(i)
      If c > b Then d = c: c = b: b = d
         gys = c
         Do Until b Mod gys = 0 And c Mod gys = 0
            gys = gys - 1
         Loop
         c = gys
    Next i
    Print "最大公约数为:"; gys
End Sub
Private Sub Form_Load()
   MeAutoRedraw = True
End Sub

'定义的是自定义函数,所以要这样写
Public Function gys(m, n)
Do
r = m Mod n
m = n
n = r
Loop Until r = 0
gys = m
End Function

'Command1_Click()里的变量都没有定义所以要定义好,如下
Private Sub Command1_Click()
Dim x As Integer, y As Integer, z As Integer
Dim t1 As Integer, t2 As Integer, t As Integer
x = Val(Text1Text)
y = Val(Text2Text)
z = Val(Text3Text)
t1 = gys(x, z)
t2 = gys(x, y)
t = gys(t1, t2)
Print t;
End Sub
这样就可以显示了,我调试过了

用for循环求最大公约数:
int gcd(int m,int n)
{int r;
if(!n)return m;
for(;r=m%n;)m=n,n=r;
return n;
}
用for循环求最小公倍数
int lcm(int m,int n)
{int r,k=mn;
if(!n)return m;
for(;r=m%n;)m=n,n=r;
return k/n;
}

单击Command1便可产生1~100内素数。代码如下。
------------------
Function IsPrime(ByVal n As Long) As Boolean
Dim i As Long
For i = 2 To Int(n / 2)
If n Mod i = 0 Then IsPrime = False: Exit Function
Next
IsPrime = True
End Function
Private Sub Command1_Click()
For i = 2 To 100
If IsPrime(i) = True Then Print i
Next
End Sub
'--------------------------------------
求两个数最大公约数的程序,格式为MaxDeno(x,y),返回x,y的最大公约数。代码如下。
'--------------------------------------
Function MaxDeno(ByVal x As Long, ByVal y As Long) As Long
While x <> y
If x > y Then
x = x - y
Else
y = y - x
End If
Wend
MaxDeno = x
End Function

Function gcd%(ByVal i%, ByVal j%)
    Dim k%
    gcd = 1
    k = 2
    Do While k <= i And k <= j
        If i Mod k = 0 And j Mod k = 0 Then
            i = i / k
            j = j / k
            gcd = gcd  k
        Else
            k = k + 1
        End If
    Loop
End Function
Sub s()
    c = InputBox("")
    a = InputBox("")
    For i = 1 To c - 1
        b = InputBox("")
        a = gcd(a, b)
    Next
    MsgBox a
End Sub


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12829758.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-28
下一篇 2023-05-28

发表评论

登录后才能评论

评论列表(0条)

保存