Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
Last Updated :
10 Apr, 2023
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.
Examples:
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).
Algorithm:
- Define a function isPrime to check if a number is prime or not
- If n <= 1, return false
- Check if n is divisible by any number between 2 and sqrt(n)
- If n is divisible by i, return false; otherwise, return true
- Define an integer array arr and calculate its length n
- Initialize two integer variables sumOfPrimes and sumOfNonPrimes to 0
- Traverse the array arr from i=0 to i=n-1
- If isPrime(arr[i]) returns true, add arr[i] to the sum of primes (sumOfPrimes += arr[i])
- Else, if arr[i] is not 1, add arr[i] to the sum of non-primes (sumOfNonPrimes += arr[i])
- Calculate the absolute difference between the sum of primes and the sum of non-primes (diff = abs(sumOfPrimes – sumOfNonPrimes))
- Print the absolute difference
Below is the implementation of the approach:
C++
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime( int n) {
if (n <= 1)
return false ;
for ( int i = 2; i <= sqrt (n); i++) {
if (n % i == 0)
return false ;
}
return true ;
}
int main() {
int arr[] = {1 ,3 ,5 ,10 ,15, 7};
int n = sizeof (arr) / sizeof (arr[0]);
int sumOfPrimes = 0, sumOfNonPrimes = 0;
for ( int i = 0; i < n; i++) {
if (isPrime(arr[i]))
sumOfPrimes += arr[i];
else if (arr[i] != 1)
sumOfNonPrimes += arr[i];
}
int diff = abs (sumOfNonPrimes - sumOfPrimes);
cout << diff << endl;
return 0;
}
|
Java
import java.util.*;
public class Main
{
public static boolean isPrime( int n) {
if (n <= 1 )
return false ;
for ( int i = 2 ; i <= Math.sqrt(n); i++) {
if (n % i == 0 )
return false ;
}
return true ;
}
public static void main(String[] args) {
int [] arr = { 1 , 3 , 5 , 10 , 15 , 7 };
int n = arr.length;
int sumOfPrimes = 0 , sumOfNonPrimes = 0 ;
for ( int i = 0 ; i < n; i++) {
if (isPrime(arr[i]))
sumOfPrimes += arr[i];
else if (arr[i] != 1 )
sumOfNonPrimes += arr[i];
}
int diff = Math.abs(sumOfNonPrimes - sumOfPrimes);
System.out.println(diff);
}
}
|
Python3
import math
def is_prime(n):
if n < = 1 :
return False
for i in range ( 2 , int (math.sqrt(n)) + 1 ):
if n % i = = 0 :
return False
return True
arr = [ 1 , 3 , 5 , 10 , 15 , 7 ]
n = len (arr)
sum_of_primes = 0
sum_of_non_primes = 0
for i in range (n):
if is_prime(arr[i]):
sum_of_primes + = arr[i]
elif arr[i] ! = 1 :
sum_of_non_primes + = arr[i]
diff = abs (sum_of_non_primes - sum_of_primes)
print (diff)
|
C#
using System;
namespace PrimeAndNonPrimeSum {
class Program {
static bool IsPrime( int n)
{
if (n <= 1)
return false ;
for ( int i = 2; i <= Math.Sqrt(n); i++) {
if (n % i == 0)
return false ;
}
return true ;
}
static void Main( string [] args)
{
int [] arr = { 1, 3, 5, 10, 15, 7 };
int n = arr.Length;
int sumOfPrimes = 0, sumOfNonPrimes = 0;
for ( int i = 0; i < n; i++) {
if (IsPrime(arr[i]))
sumOfPrimes
+= arr[i];
else if (arr[i] != 1)
sumOfNonPrimes
+= arr[i];
}
int diff = Math.Abs(sumOfNonPrimes - sumOfPrimes);
Console.WriteLine(diff);
}
}
}
|
Javascript
function isPrime(n) {
if (n <= 1) {
return false ;
}
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false ;
}
}
return true ;
}
const arr = [1, 3, 5, 10, 15, 7];
const n = arr.length;
let sumOfPrimes = 0,
sumOfNonPrimes = 0;
for (let i = 0; i < n; i++) {
if (isPrime(arr[i])) {
sumOfPrimes += arr[i];
} else if (arr[i] !== 1) {
sumOfNonPrimes += arr[i];
}
}
const diff = Math.abs(sumOfNonPrimes - sumOfPrimes);
console.log(diff);
|
Time complexity: O(N*sqrt(max(arr)))
Space Complexity: O(1)
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))
C++
#include <bits/stdc++.h>
using namespace std;
int CalculateDifference( int arr[], int n)
{
int max_val = *max_element(arr, arr + n);
vector< bool > prime(max_val + 1, true );
prime[0] = false ;
prime[1] = false ;
for ( int p = 2; p * p <= max_val; p++) {
if (prime[p] == true ) {
for ( int i = p * 2; i <= max_val; i += p)
prime[i] = false ;
}
}
int S1 = 0, S2 = 0;
for ( int i = 0; i < n; i++) {
if (prime[arr[i]]) {
S1 += arr[i];
}
else if (arr[i] != 1) {
S2 += arr[i];
}
}
return abs (S2 - S1);
}
int main()
{
int arr[] = { 1, 3, 5, 10, 15, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << CalculateDifference(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int CalculateDifference( int arr[],
int n)
{
int max_val = Integer.MIN_VALUE;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] > max_val)
max_val = arr[i];
}
boolean []prime = new boolean [max_val + 1 ];
for ( int i = 0 ; i <= max_val; i++)
prime[i] = true ;
prime[ 0 ] = false ;
prime[ 1 ] = false ;
for ( int p = 2 ;
p * p <= max_val; p++)
{
if (prime[p] == true )
{
for ( int i = p * 2 ;
i <= max_val; i += p)
prime[i] = false ;
}
}
int S1 = 0 , S2 = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (prime[arr[i]])
{
S1 += arr[i];
}
else if (arr[i] != 1 )
{
S2 += arr[i];
}
}
return Math.abs(S2 - S1);
}
public static void main(String []args)
{
int arr[] = { 1 , 3 , 5 , 10 , 15 , 7 };
int n = arr.length;
System.out.println(CalculateDifference(arr, n));
}
}
|
Python3
import sys
def CalculateDifference(arr, n):
max_val = - 1
for i in range ( 0 , n):
if (arr[i] > max_val):
max_val = arr[i]
prime = [ True for i in range (max_val + 1 )]
prime[ 0 ] = False
prime[ 1 ] = False
p = 2
while (p * p < = max_val):
if prime[p] = = True :
for i in range (p * 2 ,
max_val + 1 , p):
prime[i] = False
p + = 1
S1 = 0
S2 = 0
for i in range ( 0 , n):
if prime[arr[i]]:
S1 + = arr[i]
elif arr[i] ! = 1 :
S2 + = arr[i]
return abs (S2 - S1)
arr = [ 1 , 3 , 5 , 10 , 15 , 7 ]
n = len (arr)
print (CalculateDifference(arr, n))
|
C#
using System;
class GFG
{
static int CalculateDifference( int []arr,
int n)
{
int max_val = int .MinValue;
for ( int i = 0; i < n; i++)
{
if (arr[i] > max_val)
max_val = arr[i];
}
bool []prime = new bool [max_val + 1];
for ( int i = 0; i <= max_val; i++)
prime[i] = true ;
prime[0] = false ;
prime[1] = false ;
for ( int p = 2;
p * p <= max_val; p++)
{
if (prime[p] == true )
{
for ( int i = p * 2;
i <= max_val; i += p)
prime[i] = false ;
}
}
int S1 = 0, S2 = 0;
for ( int i = 0; i < n; i++)
{
if (prime[arr[i]])
{
S1 += arr[i];
}
else if (arr[i] != 1)
{
S2 += arr[i];
}
}
return Math.Abs(S2 - S1);
}
public static void Main( string []args)
{
int []arr = { 1, 3, 5, 10, 15, 7 };
int n = arr.Length;
Console.WriteLine(CalculateDifference(arr, n));
}
}
|
PHP
<?php
function CalculateDifference( $arr , $n )
{
$max_val = PHP_INT_MIN;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $arr [ $i ] > $max_val )
$max_val = $arr [ $i ];
}
$prime = array_fill (0, $max_val + 1, true);
$prime [0] = false;
$prime [1] = false;
for ( $p = 2; $p * $p <= $max_val ; $p ++)
{
if ( $prime [ $p ] == true)
{
for ( $i = $p * 2;
$i <= $max_val ; $i += $p )
$prime [ $i ] = false;
}
}
$S1 = 0;
$S2 = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $prime [ $arr [ $i ]])
{
$S1 += $arr [ $i ];
}
else if ( $arr [ $i ] != 1)
{
$S2 += $arr [ $i ];
}
}
return abs ( $S2 - $S1 );
}
$arr = array ( 1, 3, 5, 10, 15, 7 );
$n = sizeof( $arr );
echo CalculateDifference( $arr , $n );
?>
|
Javascript
function CalculateDifference(arr) {
let max_val = Math.max(...arr);
let prime = new Array(max_val + 1).fill( true );
prime[0] = false ;
prime[1] = false ;
for (let p = 2; p * p <= max_val; p++) {
if (prime[p] === true ) {
for (let i = p * 2; i <= max_val; i += p) {
prime[i] = false ;
}
}
}
let S1 = 0,
S2 = 0;
for (let i = 0; i < arr.length; i++) {
if (prime[arr[i]]) {
S1 += arr[i];
} else if (arr[i] !== 1) {
S2 += arr[i];
}
}
return Math.abs(S2 - S1);
}
let arr = [1, 3, 5, 10, 15, 7];
console.log(CalculateDifference(arr));
|
Time Complexity: O(n + max_val), where n is the size of the array and max_val is the maximum value in the array.
Auxiliary Space: O(max_val)
Similar Reads
Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between product of non-prime numbers and prime numbers.Note: 1 is neither prime nor non-prime.Examples: Input : arr[] = {1, 3, 5, 10, 15, 7} Output : 45 Explanation : Product of non-primes = 150 Product of primes =
15 min read
Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
Given an array arr[] of N positive integers, the task is to calculate the absolute difference between XOR of non-prime numbers and prime numbers. Note that 1 is neither prime nor composite.Examples: Input: arr[] = {1, 3, 5, 10, 15, 7} Output: 4 Xor of non-primes = 10 ^ 15 = 5 Xor of primes = 3 ^ 5 ^
8 min read
Bitwise AND of the sum of prime numbers and the sum of composite numbers in an array
Given an array of positive numbers, the task is to find the bitwise AND of the sum of non-prime numbers and the sum of prime numbers. Note that 1 is neither prime nor composite.Examples: Input: arr[] = {1, 3, 5, 10, 15, 7} Output: 9 Sum of non-primes = 10 + 15 = 25 Sum of primes = 3 + 5 + 7 = 15 25
9 min read
Pair of prime numbers with a given sum and minimum absolute difference
Given an integer 'sum' (less than 10^8), the task is to find a pair of prime numbers whose sum is equal to the given 'sum' Out of all the possible pairs, the absolute difference between the chosen pair must be minimum. If the âsumâ cannot be represented as a sum of two prime numbers then print âCann
8 min read
Difference between the largest and the smallest primes in an array
Given an array of integers where all the elements are less than 10^6. The task is to find the difference between the largest and the smallest prime numbers in the array. Examples: Input : Array = 1, 2, 3, 5 Output : Difference is 3 Explanation : The largest prime number in the array is 5 and the sma
8 min read
Count prime numbers that can be expressed as sum of consecutive prime numbers
Given an integer N, the task is to find the number of prime numbers up to N that can be expressed as a sum of consecutive primes. Examples: Input: N = 45Output: 3Explanation:Below are the prime numbers up to 45 that can be expressed as sum of consecutive prime numbers: 5 = 2 + 317 = 2 + 3 + 5 + 741
8 min read
Check if a prime number can be expressed as sum of two Prime Numbers
Given a prime number N. The task is to check if it is possible to express N as the sum of two separate prime numbers.Note: The range of N is less than 108. Examples: Input: N = 13Output: YesExplanation: The number 13 can be written as 11 + 2, here 11 and 2 are both prime.Input: N = 11Output: NoRecom
13 min read
Minimize sum of absolute difference between all pairs of array elements by decrementing and incrementing pairs by 1
Given an array arr[] ( 1-based indexing ) consisting of N integers, the task is to find the minimum sum of the absolute difference between all pairs of array elements by decrementing and incrementing any pair of elements by 1 any number of times. Examples: Input: arr[] = {1, 2, 3}Output: 0Explanatio
5 min read
Check whether the sum of absolute difference of adjacent digits is Prime or not
Given a number a N and the task is to check whether the sum of absolute difference of adjacent digit is a prime or not. Examples: Input: N = 142 Output: PrimeSum = |1-4| + |4-2| = 5 i.e. prime.Input: N = 347Output: Not prime Recommended: Please try your approach on {IDE} first, before moving on to t
15 min read
Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
Given a range [l, r]. The task is to count the numbers in the range having difference between the sum of digits at even position and sum of digits at odd position is a Prime Number. Consider the position of least significant digit in the number as an odd position. Examples: Input : l = 1, r = 50Outp
15+ min read