What does the following function do? def fun(n): d2 = set() for i in range(1,…
2025
What does the following function do?
def fun(n):
d2 = set()
for i in range(1, int(sqrt(n) + 1)):
if n % i == 0:
d2.add(i)
d2.add(n // i)
return list(d2)Answer: C. Finds all divisors of a number — For any positive integer n, its divisors always occur in pairs (i, n / i) with i ≤ √n ≤ n / i. So testing only i = 1 up to √n and checking n % i == 0 is…
- A.
Finds the prime numbers upto n
- B.
Finds remainders when divided by n
- C.
Finds all divisors of a number
- D.
Finds the GCD of a number
Attempted by 151 students.
Show answer & explanation
Correct answer: C
For any positive integer n, its divisors always occur in pairs (i, n / i) with i ≤ √n ≤ n / i. So testing only i = 1 up to √n and checking n % i == 0 is enough to find every divisor of n — each hit yields BOTH members of a divisor pair at once.
d2 = set() starts an empty collection to hold discovered divisors.
The loop runs i from 1 up to int(√n) + 1, so i only ever reaches √n (inclusive).
For n = 36: √36 = 6, so i takes values 1, 2, 3, 4, 5, 6.
i = 1: 36 % 1 == 0, so 1 and 36 // 1 = 36 are added.
i = 2: 36 % 2 == 0, so 2 and 18 are added.
i = 3: 36 % 3 == 0, so 3 and 12 are added.
i = 4: 36 % 4 == 0, so 4 and 9 are added.
i = 5: 36 % 5 != 0, nothing is added.
i = 6: 36 % 6 == 0, so 6 and 6 are added — the set silently absorbs this duplicate at the perfect-square midpoint.
The final set is {1, 2, 3, 4, 6, 9, 12, 18, 36} — exactly the divisors of 36.
This also explains why the other readings fail: it is not primality testing, because a prime check must actively reject n the moment ANY divisor besides 1 and n turns up, whereas this code unconditionally records every divisor it meets; it is not remainder-tracking, because n % i is used only as a zero/non-zero gate and the remainder value itself is never stored; and it is not a GCD routine, because GCD needs two numbers to compare and this function only ever receives one.
So the function collects both members of every (i, n // i) divisor pair for i up to √n, running in O(√n) time — it finds all divisors of a number.