Sunday, February 26, 2023
HomeSoftware EngineeringCalculating Odd/Even variety of divisors in Python

# Calculating Odd/Even variety of divisors in Python

## The problem#

Given an integer `n` return `"odd"` if the variety of its divisors is odd. In any other case, return `"even"`.

Be aware: massive inputs might be examined.

Examples:

All prime numbers have precisely two divisors (therefore `"even"`).

For `n = 12` the divisors are `[1, 2, 3, 4, 6, 12]` – `"even"`.

For `n = 4` the divisors are `[1, 2, 4]` – `"odd"`.

## The answer in Python code#

Possibility 1:

``````def oddity(n):
return 'odd' if n**0.5 == int(n**0.5) else 'even'
``````

Possibility 2:

``````import math
def oddity(n):
return math.sqrt(n) % 1 == 0 and 'odd' or 'even'
``````

Possibility 3:

``````oddity=lambda n: ["odd","even"][n**.5%1!=0]
``````

## Take a look at instances to validate our answer#

``````import check

@check.describe("Pattern exams")
def exams():
@check.it("Some examples")
def exams():
check.assert_equals(oddity(1), 'odd')
check.assert_equals(oddity(5), 'even')
check.assert_equals(oddity(16), 'odd')
``````
RELATED ARTICLES