DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Edited on

#9 - Twin Prime CodeWars Kata (6 kyu)

Instructions

A twin prime is a prime number that differs from another prime number by 2. Write a function named is_twin_prime which takes an int parameter and returns true if it is a twin prime, else false.

Example:

given 5, which is prime
5+2=7 which is prime
5-2=3 which is prime
Hence, 5 has two prime twins and its a Twin Prime.


given 7, which is prime
7-2=5 which is prime
7+2=9 which is not prime
Hence, 7 has one prime twin, and its a Twin Prime.


given 9, which is not prime
Hence, 9 is not a Twin Prime


given 953 , which is prime
953-2=951 , which is not prime
953+2=955 , which is not prime
Hence, 953 is not a Twin Prime.

My solution:

function isTwinPrime(n){

function isPrime(x){     
      let d = x-1;
      while (d > 1){
        if ((x % d) == 0) return false;
        d--;
      }
      return x > 1
}

  if(!isPrime(n)) return false

  if(isPrime(n-2) || isPrime(n+2)){
    return true
  }

  return false

}

Enter fullscreen mode Exit fullscreen mode

Explanation

I started doing a function that took a number as a paremeter and looked if it is an prime number or not.

After that I used a conditional that checked if the original number is prime, if it's not it'll return false.

Then I used another conditional for checking if the number two numbers before or two numbers after the original number are primes, if any of those are primes, it returns true.

Else it returns false

Comment how would you solve this kata and why? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (0)