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

Here we will see how we can find the absolute difference between the product of all prime numbers and all non-prime numbers of an array. To solve this problem, we have to check whether a number is prime or not. One possible way for primality testing is by checking a number is not divisible by any number between 2 to square root of that number. So this process will take O(√n) amount of time. Then get the product and try to find the absolute difference.

Syntax

int diffPrimeNonPrimeProd(int arr[], int n);
bool isPrime(int n);

Algorithm

diffPrimeNonPrimeProd(arr)

begin
   prod_p := product of all prime numbers in arr
   prod_np := product of all non-prime numbers in arr
   return |prod_p - prod_np|
end

Example

Let's implement the algorithm to find the absolute difference between products −

#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>

bool isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return false; // not prime
        }
    }
    return true; // prime
}

int diffPrimeNonPrimeProd(int arr[], int n) {
    int prod_p = 1, prod_np = 1;
    
    for (int i = 0; i < n; i++) {
        if (isPrime(arr[i])) {
            prod_p *= arr[i];
        } else {
            prod_np *= arr[i];
        }
    }
    return abs(prod_p - prod_np);
}

int main() {
    int arr[] = {4, 5, 3, 8, 13, 10};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("<br>");
    
    printf("Difference: %d<br>", diffPrimeNonPrimeProd(arr, n));
    return 0;
}

Output

Array: 4 5 3 8 13 10 
Difference: 125

How It Works

In the given array {4, 5, 3, 8, 13, 10}:

  • Prime numbers: 5, 3, 13 ? Product = 5 × 3 × 13 = 195
  • Non-prime numbers: 4, 8, 10 ? Product = 4 × 8 × 10 = 320
  • Absolute difference: |195 - 320| = 125

Key Points

  • The isPrime() function handles edge cases for numbers ? 1
  • Time complexity is O(n × ?m) where n is array size and m is the maximum element
  • We use abs() function to get the absolute difference

Conclusion

This approach efficiently calculates the absolute difference between prime and non-prime products by first identifying prime numbers using square root optimization, then computing their respective products.

Updated on: 2026-03-15T10:57:56+05:30

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements