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 numberFor 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…

  1. A.

    Finds the prime numbers upto n

  2. B.

    Finds remainders when divided by n

  3. C.

    Finds all divisors of a number

  4. 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.

  1. d2 = set() starts an empty collection to hold discovered divisors.

  2. The loop runs i from 1 up to int(√n) + 1, so i only ever reaches √n (inclusive).

  3. For n = 36: √36 = 6, so i takes values 1, 2, 3, 4, 5, 6.

  4. i = 1: 36 % 1 == 0, so 1 and 36 // 1 = 36 are added.

  5. i = 2: 36 % 2 == 0, so 2 and 18 are added.

  6. i = 3: 36 % 3 == 0, so 3 and 12 are added.

  7. i = 4: 36 % 4 == 0, so 4 and 9 are added.

  8. i = 5: 36 % 5 != 0, nothing is added.

  9. i = 6: 36 % 6 == 0, so 6 and 6 are added — the set silently absorbs this duplicate at the perfect-square midpoint.

  10. 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.

Explore the full course: Capgemini Preparation

Loading lesson…