w3resource

Python: Find the number of divisors of a given integer is even or odd


Even or Odd Divisors

Write a Python program to find the total number of even or odd divisors of a given integer.

Sample Solution:

Python Code:

# Define a function 'divisor' that calculates the number of divisors for a given integer 'n'.
def divisor(n):
    # Count the number of integers from 1 to 'n' that divide 'n' without remainder.
    x = len([i for i in range(1, n + 1) if not n % i])
    
    # Return the count of divisors.
    return x

# Test the 'divisor' function with different values of 'n' and print the results.
print(divisor(15))
print(divisor(12))
print(divisor(9))
print(divisor(6))
print(divisor(3))

Sample Output:

4
6
3
4
2

Explanation:

The above Python code defines a function named "divisor()" that calculates the number of divisors for a given integer 'n'. Here's a brief explanation:

  • Function Definition:
    • def divisor(n):: Define a function named "divisor()" that takes an integer 'n' as input.
  • Count Divisors:
    • x = len([i for i in range(1, n + 1) if not n % i]): Use a list comprehension to create a list of integers from 1 to 'n' that evenly divide 'n' (i.e., have no remainder). The length of this list is the count of divisors, and it is assigned to the variable 'x'.
  • Return Result:
    • return x: Return the count of divisors.
  • Function Testing:
    • Test the divisor function with different values of 'n' (15, 12, 9, 6, 3).
    • Print the results of the function calls.

Visual Presentation:

Python: Find the number of divisors of a given integer is even or odd

Flowchart:

Flowchart: Python - Find the number of divisors of a given integer is even or odd

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program that accept a positive number and subtract from this number the sum of its digits and so on. Continues this operation until the number is positive.
Next: Write a Python program to find the digits which are absent in a given mobile number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.