If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To find all the divisors of a given positive integer in Python, you can create a function that iterates through the numbers from 1 to the given integer and checks if they divide the number without leaving a remainder. Here's one way to find all divisors:
pythonCopy code
def find_divisors(num): divisors = [] for i in range(1, num + 1): if num % i == 0: divisors.append(i) return divisors # Example usage: num_to_check = 12 all_divisors = find_divisors(num_to_check) print(f"All divisors of {num_to_check}: {all_divisors}")
Output:
lessCopy code
All divisors of 12: [1, 2, 3, 4, 6, 12]
In this example, the
find_divisors()
function takes a positive integernum
as input and initializes an empty listdivisors
to store the divisors. The function then iterates from 1 tonum
using therange()
function. For each numberi
, it checks ifnum
is divisible byi
without leaving a remainder (num % i == 0
). If the condition is true,i
is a divisor ofnum
, and it is added to thedivisors
list.When you call the
find_divisors()
function withnum_to_check = 12
, it will find all divisors of 12, which are 1, 2, 3, 4, 6, and 12, and print the result.Keep in mind that the function also considers 1 and the number itself as divisors since every positive integer is divisible by 1 and itself. If you want to exclude 1 and the number itself from the list of divisors, you can modify the range in the loop to
range(2, num)
instead ofrange(1, num + 1)
.
Comments: 0