Check whether the sum of prime elements of the array is prime or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums. We have to check whether the sum of all prime elements in the given array is also prime or not

So, if the input is like nums = [1,2,4,5,3,3], then the output will be True as sum of all primes are (2+5+3+3) = 13 and 13 is also prime.

To solve this, we will follow these steps −

  • MAX := 10000
  • sieve := a list of size MAX and fill with true
  • Define a function generate_list_of_primes()
  • sieve[0] := False, sieve[1] := False
  • for i in range 2 to MAX - 1, do
    • if sieve[i] is true, then
      • for j in range 2^i to MAX, increase by i
        • sieve[j] := False
  • From the main method do the following:
  • generate_list_of_primes()
  • total := 0
  • for i in range 0 to size of arr - 1, do
    • if sieve[arr[i]] is true, then
      • total := total + arr[i]
  • if sieve[total] is true, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

MAX = 10000
sieve = [True] * MAX
 
def generate_list_of_primes() :
   sieve[0] = False
   sieve[1] = False
     
   for i in range(2, MAX) :
      if sieve[i] :
         for j in range(2**i, MAX, i) :
           sieve[j] = False
     
def solve(arr) :
   generate_list_of_primes()
   total = 0
   for i in range(len(arr)) :
      if sieve[arr[i]] :
         total += arr[i]

   if sieve[total] :
      return True
   return False

nums = [1,2,4,5,3,3]
print(solve(nums))

Input

[1,2,4,5,3,3]

Output

True
raja
Published on 16-Jan-2021 05:03:01
Advertisements