Skip to content

find_close_factors

Find the largest factor of a given integer n that is closest to its square root.

This function identifies the largest integer factor of n less than or equal to the square root of n.

Parameters:

Name Type Description Default
n int

The integer whose factor is to be found.

required

Returns:

Type Description
int or None

The largest factor of n closest to its square root, or None if no such factor exists.

Raises:

Type Description
ValueError

If n is not a positive integer.

Source code in tinybig/koala/algebra/numbers.py
def find_close_factors(n: int):
    """
        Find the largest factor of a given integer `n` that is closest to its square root.

        This function identifies the largest integer factor of `n` less than or equal
        to the square root of `n`.

        Parameters
        ----------
        n : int
            The integer whose factor is to be found.

        Returns
        -------
        int or None
            The largest factor of `n` closest to its square root, or `None` if no such factor exists.

        Raises
        ------
        ValueError
            If `n` is not a positive integer.

    """
    sqrt_n = int(math.isqrt(n))
    for i in range(sqrt_n, 0, -1):
        if n % i == 0:
            return i
    return None