Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Print All Divisors of a Positive Integer

Python Print All Divisors of a Positive Integer

Document Object Reference Manual Python3 Examples

In Python, we can write a simple program to find all divisors of a positive integer. A divisor is an integer that divides the number evenly. For example, the divisors of 6 are 1, 2, 3, 6.

Example

def

find_factors

(

n

)

:

    factors

=

[

]

   

for

i

in

range

(

1

,

n +

1

)

:

       

if

n % i

==

0

:

            factors.

append

(

i

)

   

return

factors

number

=

28

print

(

f

"The factors of {number} are: {find_factors(number)}"

)

Code analysis:

  1. find_factors(n) is a function used to find all divisors of the integer n .
  2. factors = [] Initialize an empty list to store the divisors found.
  3. for i in range(1, n + 1) Loop from 1 to n, checking whether each number is n a divisor of the number.
  4. if n % i == 0 Checks i Check whether it divides nevenly; if it does, then i Is n a divisor of the number.
  5. factors.append(i) Add the divisor found to the list.
  6. return factors Return the list containing all divisors.
  7. number = 28 Set the integer whose divisors are to be found.
  8. print(f"The factors of {number} are: {find_factors(number)}") Print the result.

Output result:

The factors of 28 are: [1, 2, 4, 7, 14, 28]

Document Object Reference Manual Python3 Examples