Check if N is Strong Prime in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to check whether n is a strong prime or not. As we know a number said to be strong prime when it is a prime number that is greater than the average of nearest prime numbers.

So, if the input is like num = 37, then the output will be True as nearest prime numbers are 31 and 41, the average is (31+41)/2 = 36. And 37 > 36.

To solve this, we will follow these steps −

  • if num is not prime or num is 2, then
    • return False
  • last := num - 1, next := num + 1
  • while next is not prime, do
    • next := next + 1
  • while last is not prime, do
    • last := last - 1
  • avg :=(last + next) / 2
  • if num > avg, then
    • return True
  • return False

Example

Let us see the following implementation to get better understanding −

 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 solve(num):
   if isPrime(num) == False or num == 2:
      return False
   last = num - 1
   next = num + 1
   while isPrime(next) == False:
      next += 1
   while isPrime(last) == False:
      last -= 1
   avg = (last + next) / 2
   if num > avg:
      return True
   return False
num = 37
print(solve(num))

Input

37

Output

True
raja
Published on 19-Jan-2021 09:48:24
Advertisements