Calculating Odd/Even number of divisors in Python

The challenge

Given an integer n return "odd" if the number of its divisors is odd. Otherwise, return "even".

Note: big inputs will be tested.


All prime numbers have exactly two divisors (hence "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 solution in Python code

Option 1:

def oddity(n): #your code here return 'odd' if n**0.5 == int(n**0.5) else 'even'
Code language: Python (python)

Option 2:

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

Option 3:

oddity=lambda n: ["odd","even"][n**.5%1!=0]
Code language: Python (python)

Test cases to validate our solution

import test from solution import oddity @test.describe("Sample tests") def tests():"Some examples") def tests(): test.assert_equals(oddity(1), 'odd') test.assert_equals(oddity(5), 'even') test.assert_equals(oddity(16), 'odd')
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments