Tuesday, April 23, 2024
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: large inputs will probably 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#

Choice 1:

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

Choice 2:

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

Choice 3:

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

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

``````import take a look at

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