YouTip LogoYouTip

Python Print Factors

## Python: Print All Factors of a Positive Integer In mathematics and computer science, finding the factors of an integer is a fundamental operation. A **factor** (or divisor) of a positive integer $n$ is an integer that can divide $n$ without leaving a remainder. For example, the factors of $6$ are $1, 2, 3,$ and $6$. This tutorial will guide you through writing a Python program to find and print all the factors of a given positive integer. We will cover a basic approach, analyze how it works, and then explore an optimized approach for better performance with larger numbers. --- ## 1. Basic Approach (Linear Search) The most straightforward way to find the factors of a number $n$ is to iterate through all integers from $1$ to $n$ and check if $n$ is divisible by each integer. ### Code Example ```python def find_factors(n): """ Finds and returns all factors of a positive integer n. """ factors = [] # Loop from 1 to n (inclusive) for i in range(1, n + 1): # Check if i divides n without a remainder if n % i == 0: factors.append(i) return factors # Define the number to test number = 28 # Find and print the factors result = find_factors(number) print(f"The factors of {number} are: {result}") ``` ### Output ```text The factors of 28 are: [1, 2, 4, 7, 14, 28] ``` ### Code Explanation 1. **`def find_factors(n):`** Defines a function that accepts a positive integer `n` as its parameter. 2. **`factors = []`** Initializes an empty list to store the factors as they are found. 3. **`for i in range(1, n + 1):`** Sets up a loop that iterates through every integer from $1$ up to and including $n$. 4. **`if n % i == 0:`** Uses the modulo operator (`%`) to check if the remainder of `n` divided by `i` is `0`. If it is, `i` is a factor. 5. **`factors.append(i)`** Appends the valid factor `i` to our list. 6. **`return factors`** Returns the completed list of factors. 7. **`print(...)`** Formats and displays the output using an f-string. --- ## 2. Optimized Approach (Square Root Method) While the basic approach is simple, it has a time complexity of $\mathcal{O}(n)$. If you pass a very large number (e.g., $10^9$), the loop will take a noticeable amount of time to execute. We can optimize this to $\mathcal{O}(\sqrt{n})$ by observing that factors always exist in pairs. If $i$ is a factor of $n$, then $n / i$ is also a factor. One of these factors must be less than or equal to the square root of $n$ ($\sqrt{n}$). ### Optimized Code Example ```python import math def find_factors_optimized(n): """ Finds all factors of a positive integer n in O(sqrt(n)) time. """ factors = set() # Use a set to automatically handle duplicate square roots # Loop from 1 up to the square root of n for i in range(1, int(math.isqrt(n)) + 1): if n % i == 0: factors.add(i) # Add the divisor factors.add(n // i) # Add the corresponding quotient # Return sorted list of factors return sorted(list(factors)) # Define the number to test number = 100 # Find and print the factors result = find_factors_optimized(number) print(f"The factors of {number} are: {result}") ``` ### Output ```text The factors of 100 are: [1, 2, 4, 5, 10, 20, 25, 50, 100] ``` ### Why is this better? For $n = 100$, the basic approach runs the loop **100 times**. The optimized approach only runs the loop **10 times** (since $\sqrt{100} = 10$), making it significantly faster for large inputs. --- ## 3. Comparison & Considerations | Metric | Basic Approach | Optimized Approach | | :--- | :--- | :--- | | **Time Complexity** | $\mathcal{O}(n)$ | $\mathcal{O}(\sqrt{n})$ | | **Space Complexity** | $\mathcal{O}(k)$ where $k$ is the number of factors | $\mathcal{O}(k)$ | | **Best Used For** | Small integers, educational demonstrations | Large integers, competitive programming, performance-critical apps | | **Output Order** | Naturally sorted | Requires sorting at the end | ### Key Considerations * **Input Validation:** Both methods assume the input is a positive integer ($n \ge 1$). If your application accepts user input, ensure you validate that the input is greater than zero. * **Memory Usage:** The factors are stored in a list. For extremely large numbers with many factors, memory usage will scale with the number of factors found.
← Python Print Inverted TrianglePython Negative Check β†’