有N盞燈,編號1-n , 第1個人把所有燈打開,第2個人按下所有編號為2的倍數的開關(這些燈將被關掉),第3個人按下所有編號為3的倍數的開關(其中關掉的會被打開,打開的會被關掉),以此類推 , 一共有K個人 ,問最後有哪些燈開著? 輸入 n 和 k 輸出開著燈的編號
例如輸入
n = 10
k = 5
輸出為 1 4 6 7 8 10
--------------------------------------------------------------------------------------------------------------------------
答:
Module Module1
Sub Main()
Dim n As Integer, k As Integer, person As Integer
Console.Write("n=")
n = Convert.ToInt32(Console.ReadLine)
Console.Write("K=")
k = Convert.ToInt32(Console.ReadLine)
Dim NUM(n) As Boolean
For person = 1 To k
For idx As Integer = 1 To n
If (person = 1) Then
NUM(idx) = True
Else
Dim action As Boolean = (idx) Mod person = 0
If (action) Then
NUM(idx) = Not NUM(idx)
End If
End If
Next
Next
For idx As Integer = 1 To n
If (NUM(idx)) Then
Console.Write("{0} ", idx)
End If
Next
Console.Read()
End Sub
End Module
依個人需求 做微調~!
---------------------------------------------------------------------------------------------------------------------
歡迎各位高手提出自己更有效率的想法!!不吝指教!