Check if a prime number can be expressed as sum of two Prime Numbers in Python

PythonServer Side ProgrammingProgramming

Suppose we have a prime number n. we have to check whether we can express n as x + y where x and y are also two prime numbers.

So, if the input is like n = 19, then the output will be True as we can express it like 19 = 17 + 2

To solve this, we will follow these steps −

  • Define a function isPrime() . This will take number
  • if number <= 1, then
    • return False
  • if number is same as 2, then
    • return True
  • if number is even, then
    • return False
  • for i in range 3 to integer part of ((square root of number) + 1), increase by 2, do
    • if number is divisible by i, then
      • return False
  • return True
  • From the main method do the following −
  • if isPrime(number) and isPrime(number - 2) both are true, then
    • return True
  • otherwise,
    • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

from math import sqrt
def isPrime(number):
   if number <= 1:
      return False
   if number == 2:
      return True
   if number % 2 == 0:
      return False
   for i in range(3, int(sqrt(number))+1, 2):
      if number%i == 0:
         return False
   return True
def solve(number):
   if isPrime(number) and isPrime(number - 2):
      return True
   else:
      return False
n = 19
print(solve(n))

Input

19

Output

True
raja
Published on 29-Dec-2020 12:58:49
Advertisements