Skip to content

How to satisfy Wilson Primes in Python

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)
Code language: Python (python)

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) ==
Code language: Python (python)

Option 3:

def am_i_wilson(n): return n == 5 or n == 13 or n == 563
Code language: Python (python)

Test cases to validate our solution

test.assert_equals(am_i_wilson(), 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)
Code language: Python (python)

See also  How to Convert Numeric Words into Numbers using Python
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x