
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Sum of Prime Elements in Array is Prime in Python
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
- for j in range 2^i to MAX, increase by i
- if sieve[i] is true, then
- 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[arr[i]] is true, then
- if sieve[total] is true, then
- return True
- return False
Let us see the following implementation to get better understanding −
Example Code
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
Advertisements