search

Home  >  Q&A  >  body text

java - 代码实现逻辑

现在有100个灯泡,每个灯泡都是关着的,第一趟把所有的灯泡灯泡打开,第二趟把偶数位的灯泡制反,第三趟让第3,6,9....的灯泡制反.......第100趟让第100个灯泡制反,问经过一百趟以后有多少灯泡亮着。

代码如何实现:

PHP中文网PHP中文网2817 days ago302

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:15:49

    Additional to what @hsfzxjy said

    燈泡只要有一個因數就會被開關一次
    • Because light switches are performed in multiples of i 趟開關的時候, 會把 i

    • That is to say, the light bulb with the factor i will be switched on and off during this trip

    It can be deduced from the above:

    燈泡有奇數個因數最後的結果會是亮著的 (開關奇數次, 會是亮的)

    It can be summarized as:

    完全平方數的燈泡會亮著 (因為只有完全平方數有奇數個相異因數, 其他都會有兩兩成對的相異因數)

    If you want to completely simulate this situation, here is the Python code:

    lamps = [ False for i in range(100) ]
    
    # print('starts', lamps)
    
    for i in range(1, len(lamps)+1):
        for idx, lamp in enumerate(lamps):
            if (idx + 1) % i == 0:
                lamps[idx] = not lamp
        # print(i, lamps)
    
    print(lamps.count(True))

    But based on the above conclusion, you only need to know how many perfect square numbers there are in the number of light bulbs:

    i = 1
    while i**2 <= 100:
        i += 1
    
    print(i-1)

    Questions I answered: Python-QA

    reply
    0
  • 黄舟

    黄舟2017-04-18 09:15:49

    All perfect square numbers light up

    reply
    0
  • Cancelreply