There are n doors in a row, numbered from 1 to n. All doors are initially closed. There are also n people, numbered from 1 to n.
Each person i walks through the row and toggles (flips) every i-th door. Specifically, person i flips doors i, 2i, 3i, and so on, up to n. If a door is closed, it becomes open; if it is open, it becomes closed.
After all n people have acted, return a sorted list of the door numbers that remain open.
Function Signature
def open_doors(n: int) -> list[int]:
Rules
-
Doors and people are numbered from 1, and person
i
touches only doors whose number is a multiple of
i
.
-
Return the open door numbers in ascending order.
Constraints
Examples
Input: n = 10
Output: [1, 4, 9]
After all 10 people act, doors 1, 4 and 9 remain open. Door 4 is flipped by persons 1, 2 and 4 (three times, odd), so it ends open, while door 6 is flipped by persons 1, 2, 3 and 6 (four times, even), so it ends closed.
Input: n = 1
Output: [1]
There is only one door and one person. Person 1 opens door 1, and nobody touches it again.
Input: n = 16
Output: [1, 4, 9, 16]
Door 16 is flipped by persons 1, 2, 4, 8 and 16, five times, so it ends open. The last door is included whenever n itself ends open.