Check whether given three numbers are adjacent primes in Python



Suppose we have three numbers and we have to check whether they are adjacent primes are not. The adjacent primes are prime numbers where no other prime is present between them.

So, if the input is like nums = [5,7,11], then the output will be True.

To solve this, we will follow these steps −

  • if any one of these three numbers is not prime them
    • return False
  • if next prime of x is not same as y, then
    • return False
  • if next prime of y is not same as z, then
    • return False
  • return True

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def isPrime(num):    if num > 1:       for i in range(2, num):          if num % i == 0:            return False       return True    return False     def get_next_prime(num) :    next_prime = num + 1    while not isPrime(next_prime):       next_prime += 1    return next_prime   def solve(x, y, z) :    if isPrime(x) == False or isPrime(y) == False or isPrime(z) == False :       return False      next_prime = get_next_prime(x)    if next_prime != y:       return False      if get_next_prime(y) != z:       return False      return True nums = [5,7,11] print(solve(*nums))

Input

[5,7,11] 

Output

True
Updated on: 2021-01-16T04:34:09+05:30

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements