Given an array of positive numbers, the task is to calculate the absolute difference between sum of non-prime numbers and prime numbers.
Note: 1 is neither prime nor non-prime.
Input : 1 3 5 10 15 7 Output : 10 Explanation: Sum of non-primes = 25 Sum of primes = 15 Input : 3 4 6 7 Output : 0
Naive Approach: A simple solution is to traverse the array and keep checking for every element if it is prime or not. If number is prime, then add it to sum S2 which represents the sum of primes else check if its not 1 then add it to sum of non-primes let’s say S1. After traversing the whole array, take the absolute difference between the two(S1-S2).
Time complexity: O(Nsqrt(N))
Efficient Approach: Generate all primes up to the maximum element of the array using the sieve of Eratosthenes and store them in a hash. Now, traverse the array and check if the number is present in the hash map. Then, add these numbers to sum S2 else check if it’s not 1, then add it to sum S1.
After traversing the whole array, display the absolute difference between the two.
Time Complexity: O(Nlog(log(N))
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Pair of prime numbers with a given sum and minimum absolute difference
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1
- Count of numbers upto N having absolute difference of at most K between any two adjacent digits
- Arrange first N natural numbers such that absolute difference between all adjacent elements > 1
- Print prime numbers with prime sum of digits in an array
- Count of N-digit numbers with absolute difference of adjacent digits not exceeding K | Set 2
- Count of N-digit numbers with absolute difference of adjacent digits not exceeding K
- Predict the winner of the game on the basis of absolute difference of sum by selecting numbers
- Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers
- Sum of all prime numbers in an Array
- Queries for maximum difference between prime numbers in given ranges
- Product of all prime numbers in an Array
- Remove all the prime numbers from the given array
- Find the sum of prime numbers in the Kth array
- Queries for the difference between the count of composite and prime numbers in a given range
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
- Count of numbers upto M divisible by given Prime Numbers
- Minimum and Maximum prime numbers in an array
- Sum of prime numbers in range [L, R] from given Array for Q queries
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : ihritik