
'点击窗体出现输入框,分别输入第2个整数,在窗体内就会出现最大公约数,代码如下:
Private Sub Form_Click()
Dim C As Long, D As Long, E As Long
C = InputBox("请输入第1个整数:")
D = InputBox("请输入第2个整数:")
E = Zdgys(C, D)
Print C; " 和 "; D; " 的最大公约数是:"; E
End Sub
'下面是自定义函数—最大公约数函数
Private Function Zdgys(ByVal A As Long, ByVal B As Long)
Dim R As Long
R = A Mod B
Do While R <> 0
A = B
B = R
R = A Mod B
Loop
Zdgys = B
End Function
#include <stdioh> int gcd(int a,int b)//最大公约数 { if (a<b) return gcd(b,a); else if (b==0) return a; else return gcd(b,a%b); } int lcm(int a,int b) { return ab/gcd(a,b); } main() { int a,b; scanf("%d%d",&a,&b); printf("最大公约数:%d\n",gcd(a,b)); printf("最小公倍数:%d\n",lcm(a,b)); }
Private Sub Command1_Click()
If Text1Text = "" Then
MsgBox "请输入Text1"
Exit Sub
End If
If Text2Text = "" Then
MsgBox "请输入Text2"
Exit Sub
End If
If IsNumber = True Then
Text3Text = GCD(Val(Text1Text), Val(Text2Text))
End If
End Sub
Private Sub Form_Load()
Text1Text = ""
Text2Text = ""
Text3Enabled = False
Command1Caption = "计算最大公约数"
End Sub
Private Function IsNumber() As Boolean
IsNumber = True
For i = 1 To Len(Text1Text)
If IsNumeric(Mid(Text1Text, i, 1)) = False Then
MsgBox "请输入正整数"
Text1Text = ""
IsNumber = False
Exit Function
End If
Next i
For i = 1 To Len(Text2Text)
If IsNumeric(Mid(Text2Text, i, 1)) = False Then
MsgBox "请输入正整数"
Text2Text = ""
IsNumber = False
Exit Function
End If
Next i
End Function
Private Function GCD(x As Integer, y As Integer) As Integer
Dim r As Integer
Do Until y = 0
r = x Mod y
x = y
y = r
Loop
GCD = x
End Function
辗转相除法求最大公约数
求x,y的最大公约数,就用 x/y 求的余数 reminder ,如果reminder=0则 y 就是最大公约数,如果reminder<>0 则,让把y值附给x,reminder值附给y,再相除,直到余数=0 时,除数 y 的值就是最大公约数!
举例:
x=9:y=3
求最大公约数:
x mod y =0 则最大公约数是此时的y值:3
再如:x=3,y=9
x mod y =3 余数<>0 ,则执行 x=y:y=reminder后
x=3:y=3
再执行 x mod y 则 3 mod 3 =0,此时 y=3,则最大公约数=3
Private Sub Form_Click()
Dim N As Integer, M As Integer, G As Integer
N = InputBox("输入 N ")
M = InputBox("输入 M ")
G = Gcd(N, M)
Print N; " 和 "; M; " 的最大公约数是:"; G
End Sub
Private Function Gcd(ByVal A As Integer, ByVal B As Integer)
Dim R As Integer
R = A Mod B
Do While R <> 0
A = B
B = R
R = A Mod B
Loop
Gcd = B
End Function
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)