DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on

#3 - Wilson primes CodeWars Kata (8 kyu)

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.

My solution:

function amIWilson(p) {
  const factorial = (n)=>{
    if (n < 0) return -1
    if (n === 0) return 1

    return n * factorial(n - 1)

  if( ((factorial(p-1) + 1) % (p * p)) == 0) return true

  return false
Enter fullscreen mode Exit fullscreen mode

The Kata instructions say that a Wilson Prime is a number in which the result of the factorial of p-1 + 1 divided by p*p is an integer.

So first I started making a function that gets the factorial of p-1, in which I used recursive code using 2 conditionals at the beggining of the function if the passed numer is equal to zero or if it is less than zero, so it doesn't end on an infinite loop and then I recalled the same function until n equals 0.
Then I passed the formula of the Wilson Primes to a conditional with the modulus operator so it returns the reminder of the division and if the reminder is 0 it means that it is an integer and the result should be true, if the condition is false then it isn't a Wilson Prime and it'll return false

My Github
My twitter
Solve this Kata

Top comments (0)