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 = 105
Input : arr[] = {3, 4, 6, 7}
Output : 3
Naive Approach: A simple solution is to traverse the array and keep checking for every element if it is prime or not. If the number is prime, then multiply it to product P2 which represents the product of primes else check if it’s not 1 then multiply it to the product of non-primes let’s say P1. After traversing the whole array, take the absolute difference between the two(P1-P2).
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int num)
{
if (num <= 1) {
return false ;
}
for ( int i = 2; i <= sqrt (num); i++) {
if (num % i == 0) {
return false ;
}
}
return true ;
}
int calculateDifference( int arr[], int n)
{
int P1 = 1, P2 = 1;
for ( int i = 0; i < n; i++) {
if (isPrime(arr[i])) {
P1 *= arr[i];
}
else if (arr[i] != 1) {
P2 *= arr[i];
}
}
return abs (P2 - P1);
}
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 {
public static boolean isPrime( int num)
{
if (num <= 1 ) {
return false ;
}
for ( int i = 2 ; i <= Math.sqrt(num); i++) {
if (num % i == 0 ) {
return false ;
}
}
return true ;
}
public static int calculateDifference( int arr[], int n)
{
int P1 = 1 , P2 = 1 ;
for ( int i = 0 ; i < n; i++) {
if (isPrime(arr[i])) {
P1 *= arr[i];
}
else if (arr[i] != 1 ) {
P2 *= arr[i];
}
}
return Math.abs(P2 - P1);
}
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 math
def isPrime(num):
if num < = 1 :
return False
for i in range ( 2 , int (math.sqrt(num)) + 1 ):
if num % i = = 0 :
return False
return True
def calculateDifference(arr, n):
P1, P2 = 1 , 1
for i in range (n):
if isPrime(arr[i]):
P1 * = arr[i]
elif arr[i] ! = 1 :
P2 * = arr[i]
return abs (P2 - P1)
arr = [ 1 , 3 , 5 , 10 , 15 , 7 ]
n = len (arr)
print (calculateDifference(arr, n))
|
C#
using System;
public class Program
{
public static bool IsPrime( int num)
{
if (num <= 1) {
return false ;
}
for ( int i = 2; i <= Math.Sqrt(num); i++) {
if (num % i == 0) {
return false ;
}
}
return true ;
}
public static int CalculateDifference( int [] arr, int n)
{
int P1 = 1, P2 = 1;
for ( int i = 0; i < n; i++) {
if (IsPrime(arr[i])) {
P1 *= arr[i];
}
else if (arr[i] != 1) {
P2 *= arr[i];
}
}
return Math.Abs(P2 - P1);
}
public static void Main()
{
int [] arr = { 1, 3, 5, 10, 15, 7 };
int n = arr.Length;
Console.WriteLine(CalculateDifference(arr, n));
}
}
|
Javascript
function isPrime(num) {
if (num <= 1) {
return false ;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false ;
}
}
return true ;
}
function calculateDifference(arr, n) {
let P1 = 1, P2 = 1;
for (let i = 0; i < n; i++) {
if (isPrime(arr[i])) {
P1 *= arr[i];
}
else if (arr[i] !== 1) {
P2 *= arr[i];
}
}
return Math.abs(P2 - P1);
}
let arr = [1, 3, 5, 10, 15, 7];
let n = arr.length;
console.log(calculateDifference(arr, n));
|
Time Complexity: O(N*sqrt(N))
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, multiply these numbers to product P2 else check if it’s not 1, then multiply it to product P1. After traversing the whole array, display the absolute difference between the two.
Below is the implementation of the above approach:
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 P1 = 1, P2 = 1;
for ( int i = 0; i < n; i++) {
if (prime[arr[i]]) {
P1 *= arr[i];
}
else if (arr[i] != 1) {
P2 *= arr[i];
}
}
return abs (P2 - P1);
}
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.*;
import java.util.Arrays;
import java.util.Collections;
class GFG{
public static int calculateDifference( int []arr, int n)
{
int max_val = Arrays.stream(arr).max().getAsInt();
boolean [] prime = new boolean [max_val + 1 ];
Arrays.fill(prime, 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 P1 = 1 , P2 = 1 ;
for ( int i = 0 ; i < n; i++) {
if (prime[arr[i]]) {
P1 *= arr[i];
}
else if (arr[i] != 1 ) {
P2 *= arr[i];
}
}
return Math.abs(P2 - P1);
}
public static void main(String []args)
{
int [] arr = new int []{ 1 , 3 , 5 , 10 , 15 , 7 };
int n = arr.length;
System.out.println(calculateDifference(arr, n));
System.exit( 0 );
}
}
|
Python3
def calculateDifference(arr, n):
max_val = max (arr)
prime = (max_val + 1 ) * [ True ]
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
P1 = 1 ; P2 = 1
for i in range (n):
if prime[arr[i]]:
P1 * = arr[i]
elif arr[i] ! = 1 :
P2 * = arr[i]
return abs (P2 - P1)
if __name__ = = '__main__' :
arr = [ 1 , 3 , 5 , 10 , 15 , 7 ]
n = len (arr)
print (calculateDifference(arr, n))
|
C#
using System;
using System.Linq;
class GFG{
static int calculateDifference( int []arr, int n)
{
int max_val = arr.Max();
var prime = Enumerable.Repeat( true ,
max_val+1).ToArray();
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 P1 = 1, P2 = 1;
for ( int i = 0; i < n; i++) {
if (prime[arr[i]]) {
P1 *= arr[i];
}
else if (arr[i] != 1) {
P2 *= arr[i];
}
}
return Math.Abs(P2 - P1);
}
public static void Main()
{
int [] arr = new int []{ 1, 3, 5, 10, 15, 7 };
int n = arr.Length;
Console.WriteLine(calculateDifference(arr, n));
}
}
|
PHP
<?php
function calculateDifference( $arr , $n ){
$max_val = max( $arr );
$prime = array_fill (0 , $max_val ,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;
}
}
$P1 = 1;
$P2 = 1;
for ( $i = 0; $i < $n ; $i ++) {
if ( $prime [ $arr [ $i ]]) {
$P1 *= $arr [ $i ];
}
else if ( $arr [ $i ] != 1) {
$P2 *= $arr [ $i ];
}
}
return abs ( $P2 - $P1 );
}
$arr = array ( 1, 3, 5, 10, 15, 7 );
$n = count ( $arr , COUNT_NORMAL);
echo CalculateDifference( $arr , $n );
?>
|
Javascript
<script>
function calculateDifference(arr , n)
{
var max_val = Math.max.apply(Math,arr);
var prime = Array(max_val + 1).fill( 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 ;
}
}
var P1 = 1, P2 = 1;
for (i = 0; i < n; i++) {
if (prime[arr[i]]) {
P1 *= arr[i];
} else if (arr[i] != 1) {
P2 *= arr[i];
}
}
return Math.abs(P2 - P1);
}
var arr = [ 1, 3, 5, 10, 15, 7 ];
var n = arr.length;
document.write(calculateDifference(arr, n));
</script>
|
Time Complexity: O(N * log(log(N))
Space Complexity: O(MAX(N, max_val)), where max_val is the maximum value of an element in the given array.
Last Updated :
18 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...