Absolute Difference between the Sum of Non | C ++ program to find the Absolute Difference between the Sum of Non - Prime numbers and Prime numbers of an Array ; Function to find the difference between the sum of non - primes and the sum of primes of an array . ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the sum of primes in S1 and the sum of non primes in S2 ; the number is prime ; the number is non - prime ; Return the absolute difference ; Driver Code ; Get the array ; Find the absolute difference
#include <bits/stdc++.h> NEW_LINE 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 ; }