How to satisfy Wilson Primes in Python

0 min read 126 words

The challenge

Wilson primes satisfy the following condition. Let P represent a prime number.

Then ((P-1)! + 1) / (P * P) should give a whole number.

Your task is to create a function that returns true if the given number is a Wilson prime.

The solution in Python code

Option 1:

def am_i_wilson(n):
    return n in (5, 13, 563)

Option 2:

def am_i_wilson(n):
    if n < 2 or not all(n % i for i in xrange(2, n)):
        return False
    
    import math
    return (math.factorial(n - 1) + 1) % (n ** 2) == 0

Option 3:

def am_i_wilson(n):
    return n == 5 or n == 13 or n == 563

Test cases to validate our solution

test.assert_equals(am_i_wilson(0), False)
test.assert_equals(am_i_wilson(1), False)
test.assert_equals(am_i_wilson(5), True)
test.assert_equals(am_i_wilson(8), False)
test.assert_equals(am_i_wilson(9), False)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags