Skip to content

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.

Examples:

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 == and 'odd' or 'even'
Code language: Python (python)

Option 3:

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

Test cases to validate our solution

import test from solution import oddity @test.describe("Sample tests") def tests(): @test.it("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)

See also  How to satisfy Wilson Primes in Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x