Open In App

Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array

Improve
Improve
Like Article
Like
Save
Share
Report

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;
 
// Function to check if a number is prime or not
bool isPrime(int n) {
    if (n <= 1)  // 1 is not considered prime
        return false;
 
    // Check if n is divisible by any number between 2 and sqrt(n)
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0)  // If n is divisible by i, it is not prime
            return false;
    }
 
    // If n is not divisible by any number between 2 and sqrt(n), it is prime
    return true;
}
 
int main() {
    int arr[] = {1 ,3 ,5 ,10 ,15, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    int sumOfPrimes = 0, sumOfNonPrimes = 0;
 
    // Traverse the array and add primes and non-primes to their respective sums
    for (int i = 0; i < n; i++) {
        if (isPrime(arr[i]))
            sumOfPrimes += arr[i];  // Add arr[i] to the sum of primes if it is prime
        else if (arr[i] != 1)
            sumOfNonPrimes += arr[i];  // Add arr[i] to the sum of non-primes if it is not 1
    }
 
    // Calculate the absolute difference between the sums
    int diff = abs(sumOfNonPrimes - sumOfPrimes);
 
    // Print the absolute difference
    cout << diff << endl;
 
    return 0;
}


Java




import java.util.*;
 
public class Main
{
   
    // Function to check if a number is prime or not
    public static boolean isPrime(int n) {
        if (n <= 1// 1 is not considered prime
            return false;
 
        // Check if n is divisible by any number between 2 and sqrt(n)
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0// If n is divisible by i, it is not prime
                return false;
        }
 
        // If n is not divisible by any number between 2 and sqrt(n), it is prime
        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;
 
        // Traverse the array and add primes and non-primes to their respective sums
        for (int i = 0; i < n; i++) {
            if (isPrime(arr[i]))
                sumOfPrimes += arr[i];  // Add arr[i] to the sum of primes if it is prime
            else if (arr[i] != 1)
                sumOfNonPrimes += arr[i];  // Add arr[i] to the sum of non-primes if it is not 1
        }
 
        // Calculate the absolute difference between the sums
        int diff = Math.abs(sumOfNonPrimes - sumOfPrimes);
 
        // Print the absolute difference
        System.out.println(diff);
    }
}


Python3




import math
 
# Function to check if a number is prime or not
def is_prime(n):
    if n <= 1# 1 is not considered prime
        return False
 
    # Check if n is divisible by any number between 2 and sqrt(n)
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0# If n is divisible by i, it is not prime
            return False
 
    # If n is not divisible by any number between 2 and sqrt(n), it is prime
    return True
 
arr = [1, 3, 5, 10, 15, 7]
n = len(arr)
sum_of_primes = 0
sum_of_non_primes = 0
 
# Traverse the array and add primes and non-primes to their respective sums
for i in range(n):
    if is_prime(arr[i]):
        sum_of_primes += arr[i]  # Add arr[i] to the sum of primes if it is prime
    elif arr[i] != 1:
        sum_of_non_primes += arr[i]  # Add arr[i] to the sum of non-primes if it is not 1
 
# Calculate the absolute difference between the sums
diff = abs(sum_of_non_primes - sum_of_primes)
 
# Print the absolute difference
print(diff)


C#




using System;
 
namespace PrimeAndNonPrimeSum {
class Program {
    static bool IsPrime(int n)
    {
        if (n <= 1) // 1 is not considered prime
            return false;
        // Check if n is divisible by any number between 2
        // and sqrt(n)
        for (int i = 2; i <= Math.Sqrt(n); i++) {
            if (n % i == 0) // If n is divisible by i, it is
                            // not prime
                return false;
        }
 
        // If n is not divisible by any number between 2 and
        // sqrt(n), it is prime
        return true;
    }
 
    static void Main(string[] args)
    {
        int[] arr = { 1, 3, 5, 10, 15, 7 };
        int n = arr.Length;
        int sumOfPrimes = 0, sumOfNonPrimes = 0;
 
        // Traverse the array and add primes and non-primes
        // to their respective sums
        for (int i = 0; i < n; i++) {
            if (IsPrime(arr[i]))
                sumOfPrimes
                    += arr[i]; // Add arr[i] to the sum of
                               // primes if it is prime
            else if (arr[i] != 1)
                sumOfNonPrimes
                    += arr[i]; // Add arr[i] to the sum of
                               // non-primes if it is not 1
        }
 
        // Calculate the absolute difference between the
        // sums
        int diff = Math.Abs(sumOfNonPrimes - sumOfPrimes);
 
        // Print the absolute difference
        Console.WriteLine(diff);
    }
}
}
// This code is contributed by sarojmcy2e


Javascript




// Function to check if a number is prime or not
function isPrime(n) {
    if (n <= 1) {
        // 1 is not considered prime
        return false;
    }
 
    // Check if n is divisible by any number between 2 and sqrt(n)
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) {
            // If n is divisible by i, it is not prime
            return false;
        }
    }
 
    // If n is not divisible by any number between 2 and sqrt(n), it is prime
    return true;
}
 
const arr = [1, 3, 5, 10, 15, 7];
const n = arr.length;
let sumOfPrimes = 0,
    sumOfNonPrimes = 0;
 
// Traverse the array and add primes and non-primes to their respective sums
for (let i = 0; i < n; i++) {
    if (isPrime(arr[i])) {
        // Add arr[i] to the sum of primes if it is prime
        sumOfPrimes += arr[i];
    } else if (arr[i] !== 1) {
        // Add arr[i] to the sum of non-primes if it is not 1
        sumOfNonPrimes += arr[i];
    }
}
 
// Calculate the absolute difference between the sums
const diff = Math.abs(sumOfNonPrimes - sumOfPrimes);
 
// Print the absolute difference
console.log(diff);
// This code is contributed by user_dtewbxkn77n


Output

10

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++




// C++ program to find the Absolute Difference
// between the Sum of Non-Prime numbers
// and Prime numbers of an Array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the difference between
// the sum of non-primes and the
// sum of primes of an array.
int CalculateDifference(int arr[], int n)
{
    // Find maximum value in the array
    int max_val = *max_element(arr, arr + n);
 
    // 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.
    vector<bool> prime(max_val + 1, true);
 
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (int p = 2; p * p <= max_val; p++) {
 
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            for (int i = p * 2; i <= max_val; i += p)
                prime[i] = false;
        }
    }
 
    // Store the sum of primes in S1 and
    // the sum of non primes in S2
    int S1 = 0, S2 = 0;
    for (int i = 0; i < n; i++) {
 
        if (prime[arr[i]]) {
 
            // the number is prime
            S1 += arr[i];
        }
        else if (arr[i] != 1) {
 
            // the number is non-prime
            S2 += arr[i];
        }
    }
 
    // Return the absolute difference
    return abs(S2 - S1);
}
 
int main()
{
 
    // Get the array
    int arr[] = { 1, 3, 5, 10, 15, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Find the absolute difference
    cout << CalculateDifference(arr, n);
 
    return 0;
}


Java




// Java program to find the Absolute
// Difference between the Sum of
// Non-Prime numbers and Prime numbers
// of an Array
import java.util.*;
 
class GFG
{
 
// Function to find the difference
// between the sum of non-primes
// and the sum of primes of an array.
static int CalculateDifference(int arr[],
                               int n)
{
    // Find maximum value in the array
    int max_val = Integer.MIN_VALUE;
    for(int i = 0; i < n; i++)
    {
        if(arr[i] > max_val)
            max_val = arr[i];
    }
 
    // 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.
    boolean []prime = new boolean[max_val + 1];
     
    for(int i = 0; i <= max_val; i++)
        prime[i] = true;
 
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (int p = 2;
             p * p <= max_val; p++)
    {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
 
            // Update all multiples of p
            for (int i = p * 2;
                     i <= max_val; i += p)
                prime[i] = false;
        }
    }
 
    // Store the sum of primes in
    // S1 and the sum of non
    // primes in S2
    int S1 = 0, S2 = 0;
    for (int i = 0; i < n; i++)
    {
 
        if (prime[arr[i]])
        {
 
            // the number is prime
            S1 += arr[i];
        }
        else if (arr[i] != 1)
        {
 
            // the number is non-prime
            S2 += arr[i];
        }
    }
 
    // Return the absolute difference
    return Math.abs(S2 - S1);
}
 
// Driver Code
public static void main(String []args)
{
 
    // Get the array
    int arr[] = { 1, 3, 5, 10, 15, 7 };
    int n = arr.length;
 
    // Find the absolute difference
    System.out.println(CalculateDifference(arr, n));
}
}
 
// This code is contributed
// by ihritik


Python3




# Python3 program to find the Absolute
# Difference between the Sum of Non-Prime
# numbers and Prime numbers of an Array
import sys
 
# Function to find the difference
# between the sum of non-primes
# and the sum of primes of an array.
def CalculateDifference(arr, n):
 
    # Find maximum value in the array
    max_val = -1
    for i in range(0, n):
        if(arr[i] > max_val):
            max_val = arr[i]
     
    # 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.
    prime = [True for i in range(max_val + 1)]
 
    # Remaining part of SIEVE
    prime[0] = False
    prime[1] = False
    p = 2
    while (p * p <= max_val):
         
        # If prime[p] is not changed,
        # then it is a prime
        if prime[p] == True:
             
            # Update all multiples of p
            for i in range(p * 2,
                           max_val + 1, p):
                prime[i] = False
        p += 1
 
    # Store the sum of primes in
    # S1 and the sum of non primes
    # in S2
    S1 = 0
    S2 = 0
    for i in range (0, n):
 
        if prime[arr[i]]:
 
            # the number is prime
            S1 += arr[i]
         
        elif arr[i] != 1:
 
            # the number is non-prime
            S2 += arr[i]
 
    # Return the absolute difference
    return abs(S2 - S1)
 
# Driver code
     
# Get the array
arr = [ 1, 3, 5, 10, 15, 7 ]
n = len(arr)
 
# Find the absolute difference
print(CalculateDifference(arr, n))
 
# This code is contributed
# by ihritik


C#




// C# program to find the Absolute
// Difference between the Sum of
// Non-Prime numbers and Prime
// numbers of an Array
using System;
 
class GFG
{
 
// Function to find the difference
// between the sum of non-primes
// and the sum of primes of an array.
static int CalculateDifference(int []arr,
                               int n)
{
    // Find maximum value in the array
    int max_val = int.MinValue;
    for(int i = 0; i < n; i++)
    {
        if(arr[i] > max_val)
            max_val = arr[i];
    }
 
    // 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.
    bool []prime = new bool[max_val + 1];
     
    for(int i = 0; i <= max_val; i++)
        prime[i] = true;
 
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (int p = 2;
             p * p <= max_val; p++)
    {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
 
            // Update all multiples of p
            for (int i = p * 2;
                     i <= max_val; i += p)
                prime[i] = false;
        }
    }
 
    // Store the sum of primes in
    // S1 and the sum of non primes
    // in S2
    int S1 = 0, S2 = 0;
    for (int i = 0; i < n; i++)
    {
        if (prime[arr[i]])
        {
 
            // the number is prime
            S1 += arr[i];
        }
        else if (arr[i] != 1)
        {
 
            // the number is non-prime
            S2 += arr[i];
        }
    }
 
    // Return the absolute difference
    return Math.Abs(S2 - S1);
}
 
// Driver Code
public static void Main(string []args)
{
 
    // Get the array
    int []arr = { 1, 3, 5, 10, 15, 7 };
    int n = arr.Length;
 
    // Find the absolute difference
    Console.WriteLine(CalculateDifference(arr, n));
}
}
 
// This code is contributed
// by ihritik


PHP




<?php
// PHP 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.
function CalculateDifference($arr, $n)
{
    // Find maximum value in the array
    $max_val = PHP_INT_MIN;
    for($i = 0; $i < $n; $i++)
    {
        if($arr[$i] > $max_val)
            $max_val = $arr[$i];
    }
 
    // 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.
    $prime = array_fill(0, $max_val + 1, true);
 
    // Remaining part of SIEVE
    $prime[0] = false;
    $prime[1] = false;
     
    for ($p = 2; $p * $p <= $max_val; $p++)
    {
 
        // If prime[p] is not changed,
        // then it is a prime
        if ($prime[$p] == true)
        {
 
            // Update all multiples of p
            for ($i = $p * 2;
                 $i <= $max_val; $i += $p)
                $prime[$i] = false;
        }
    }
 
    // Store the sum of primes in
    // S1 and the sum of non
    // primes in S2
    $S1 = 0;
    $S2 = 0;
    for ($i = 0; $i < $n; $i++)
    {
 
        if ($prime[$arr[$i]])
        {
 
            // the number is prime
            $S1 += $arr[$i];
        }
        else if ($arr[$i] != 1)
        {
 
            // the number is non-prime
            $S2 += $arr[$i];
        }
    }
 
    // Return the absolute difference
    return abs($S2 - $S1);
}
 
// Driver code
     
// Get the array
$arr = array( 1, 3, 5, 10, 15, 7 );
$n = sizeof($arr);
 
// Find the absolute difference
echo CalculateDifference($arr, $n);
 
// This code is contributed
// by ihritik
?>


Javascript




// JavaScript 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.
function CalculateDifference(arr) {
    // Find maximum value in the array
    let max_val = Math.max(...arr);
 
    // 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.
    let prime = new Array(max_val + 1).fill(true);
 
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (let p = 2; p * p <= max_val; p++) {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] === true) {
 
            // Update all multiples of p
            for (let i = p * 2; i <= max_val; i += p) {
                prime[i] = false;
            }
        }
    }
 
    // Store the sum of primes in
    // S1 and the sum of non
    // primes in S2
    let S1 = 0,
        S2 = 0;
    for (let i = 0; i < arr.length; i++) {
 
        if (prime[arr[i]]) {
 
            // the number is prime
            S1 += arr[i];
        } else if (arr[i] !== 1) {
 
            // the number is non-prime
            S2 += arr[i];
        }
    }
 
    // Return the absolute difference
    return Math.abs(S2 - S1);
}
 
// Driver Code
let arr = [1, 3, 5, 10, 15, 7];
console.log(CalculateDifference(arr));
//This code is contributed by sarojmcy2e


Output: 

10

 

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)



Last Updated : 10 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads