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
- Arrange first N natural numbers such that absolute difference between all adjacent elements > 1
- 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
- Queries for maximum difference between prime numbers in given ranges
- Print prime numbers with prime sum of digits in an 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
- Check whether the sum of absolute difference of adjacent digits is Prime or not
- Minimum absolute difference of a number and its closest prime
- Sum of all prime numbers in an Array
- Product of all prime numbers in an Array
- Minimum and Maximum prime numbers in an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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