Responsive Navbar with Google Search
Basic Python Programs: Finding Factors of an Integer

Finding Factors of an Integer: Program 1

Finding Factors of n

n = 150: The variable n is initialized with the value 150. This is the number for which we want to find factors.

Initialize an Empty List:

factors = []: An empty list named factors is created to store the factors of \( n \).

Loop through Possible Factors:

The for loop iterates through all integers from 1 to int(n) + 1: \( \text{int}(\sqrt{n}) \) calculates the integer value of the square root of \( n \) (which is \( \sqrt{150} \approx 12.247 \), so the loop will run until 12). By looping only up to the square root, we can significantly reduce the number of iterations compared to looping all the way to \( n \). This works because factors larger than the square root will always have corresponding smaller factors.

Check for Factors:

Inside the loop, the condition if n % i == 0: checks if \( n \) is divisible by \( i \): If this condition is true, it means \( i \) is a factor of \( n \), and it is added to the factors list.

Add the Corresponding Factor:

The line if i != n // i: checks if \( i \) and its corresponding factor \( \frac{n}{i} \) are different: If they are different, the corresponding factor (which is \( n \) divided by \( i \)) is also added to the factors list. This prevents adding the square root twice if \( n \) is a perfect square.

Output 1