Dim perm_num() As Integer '用來存產生的"排列"組 ex. 當輸入12 perm_num(0)=12 perm_num(0)=21 Dim perm_count As Integer ' Sub Main() Dim infile As System.IO.StreamReader Dim i, tmp As Integer Dim arr_len As Integer My.Computer.FileSystem.WriteAllText(".\out.txt", "", False) '清空out.txt Dim j, k As Integer Dim para_str() As String '讀入的參數字串 '由檔案讀入 infile = My.Computer.FileSystem.OpenTextFileReader(".\in" & x & ".txt") arr_len = infile.ReadLine() For y = 0 To arr_len - 1 para_str = Strings.Split(infile.ReadLine(), " ") Dim ar(Len(para_str(0))) As Integer j = Integer.Parse(para_str(1)) k = Integer.Parse(para_str(2)) For i = 1 To Len(para_str(0)) ar(i) = Integer.Parse(Mid(para_str(0), i, 1)) Next '輸入數字若為n位數,則有n!種排列 tmp = 1 For i = 2 To Len(para_str(0)) tmp = tmp * i Next ReDim perm_num(tmp - 1) '重新分配Array大小 perm_count = 0 perm(ar, 1, Len(para_str(0))) '產生排列組 Array.Sort(perm_num) '排序"排列"組(考試不能用內建的函數嗎?) My.Computer.FileSystem.WriteAllText(".\out.txt", GCD(perm_num(j - 1), perm_num(k - 1)) & vbCrLf, True) Next My.Computer.FileSystem.WriteAllText(".\out.txt", vbCrLf, True) End Sub Function GCD(ByVal x As Integer, ByVal y As Integer) '求最大公因數 If x Mod y <> 0 Then GCD = GCD(y, x Mod y) Else GCD = y End If End Function Dim tmp_str As String 'Ref:http://www.blueshop.com.tw/board/FUM20050124191756KKC/BRD20051124010744UJK.html Sub perm(ByVal ar() As Integer, ByVal x As Integer, ByVal n As Integer) Dim i As Integer If x = n + 1 Then tmp_str = "" For i = 1 To n tmp_str = tmp_str & ar(i) Next perm_num(perm_count) = Integer.Parse(tmp_str) '存到陣列去,用全域變數 perm_count = perm_count + 1 End If For i = x To n swap(ar(x), ar(i)) perm(ar, x + 1, n) swap(ar(x), ar(i)) Next End Sub Sub swap(ByRef x As Integer, ByRef y As Integer) Dim tmp As Integer tmp = x x = y y = tmp End Sub