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++ code for above approach #include <bits/stdc++.h> using namespace std;
// Function to check whether the // number is prime or not 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 ;
} // Function to find the difference between // the product of non-primes and the // product of primes of an array. int calculateDifference( int arr[], int n)
{ // Store the product of primes in P1 and
// the product of non primes in P2
int P1 = 1, P2 = 1;
// Iterate on arr
for ( int i = 0; i < n; i++) {
if (isPrime(arr[i])) {
// the number is prime
P1 *= arr[i];
}
else if (arr[i] != 1) {
// the number is non-prime
P2 *= arr[i];
}
}
// Return the absolute difference
return abs (P2 - P1);
} // Driver code int main()
{ 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 code for above approach import java.util.*;
class GFG {
// Function to check whether the
// number is prime or not
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 ;
}
// Function to find the difference between
// the product of non-primes and the
// product of primes of an array.
public static int calculateDifference( int arr[], int n)
{
// Store the product of primes in P1 and
// the product of non primes in P2
int P1 = 1 , P2 = 1 ;
// Iterate on arr
for ( int i = 0 ; i < n; i++) {
if (isPrime(arr[i])) {
// the number is prime
P1 *= arr[i];
}
else if (arr[i] != 1 ) {
// the number is non-prime
P2 *= arr[i];
}
}
// Return the absolute difference
return Math.abs(P2 - P1);
}
// Driver code
public static void main(String[] args)
{
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 prasad264 |
# python code for above approach import math
# Function to check whether the # number is prime or not 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
# Function to find the difference between # the product of non-primes and the # product of primes of an array. def calculateDifference(arr, n):
# Store the product of primes in P1 and
# the product of non primes in P2
P1, P2 = 1 , 1
# Iterate on arr
for i in range (n):
if isPrime(arr[i]):
# the number is prime
P1 * = arr[i]
elif arr[i] ! = 1 :
# the number is non-prime
P2 * = arr[i]
# Return the absolute difference
return abs (P2 - P1)
# Driver code arr = [ 1 , 3 , 5 , 10 , 15 , 7 ]
n = len (arr)
# Find the absolute difference print (calculateDifference(arr, n))
|
using System;
public class Program
{ // Function to check whether the
// number is prime or not
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 ;
}
// Function to find the difference between
// the product of non-primes and the
// product of primes of an array.
public static int CalculateDifference( int [] arr, int n)
{
// Store the product of primes in P1 and
// the product of non primes in P2
int P1 = 1, P2 = 1;
// Iterate on arr
for ( int i = 0; i < n; i++) {
if (IsPrime(arr[i])) {
// the number is prime
P1 *= arr[i];
}
else if (arr[i] != 1) {
// the number is non-prime
P2 *= arr[i];
}
}
// Return the absolute difference
return Math.Abs(P2 - P1);
}
// Driver code
public static void Main()
{
int [] arr = { 1, 3, 5, 10, 15, 7 };
int n = arr.Length;
// Find the absolute difference
Console.WriteLine(CalculateDifference(arr, n));
}
} |
// JavaScript code for above approach // Function to check whether the // number is prime or not 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 to find the difference between // the product of non-primes and the // product of primes of an array. function calculateDifference(arr, n) {
// Store the product of primes in P1 and
// the product of non primes in P2
let P1 = 1, P2 = 1;
// Iterate on arr
for (let i = 0; i < n; i++) {
if (isPrime(arr[i])) {
// the number is prime
P1 *= arr[i];
}
else if (arr[i] !== 1) {
// the number is non-prime
P2 *= arr[i];
}
}
// Return the absolute difference
return Math.abs(P2 - P1);
} // Driver code let arr = [1, 3, 5, 10, 15, 7]; let n = arr.length; // Find the absolute difference console.log(calculateDifference(arr, n)); |
45
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++ program to find the Absolute Difference // between the Product of Non-Prime numbers // and Prime numbers of an Array #include <bits/stdc++.h> using namespace std;
// Function to find the difference between // the product of non-primes and the // product 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 product of primes in P1 and
// the product of non primes in P2
int P1 = 1, P2 = 1;
for ( int i = 0; i < n; i++) {
if (prime[arr[i]]) {
// the number is prime
P1 *= arr[i];
}
else if (arr[i] != 1) {
// the number is non-prime
P2 *= arr[i];
}
}
// Return the absolute difference
return abs (P2 - P1);
} // Driver Code int main()
{ 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 program to find the Absolute Difference // between the Product of Non-Prime numbers // and Prime numbers of an Array import java.util.*;
import java.util.Arrays;
import java.util.Collections;
class GFG{
// Function to find the difference between
// the product of non-primes and the
// product of primes of an array.
public static int calculateDifference( int []arr, int n)
{
// Find maximum value in the array
int max_val = Arrays.stream(arr).max().getAsInt();
// 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 ];
Arrays.fill(prime, 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 product of primes in P1 and
// the product of non primes in P2
int P1 = 1 , P2 = 1 ;
for ( int i = 0 ; i < n; i++) {
if (prime[arr[i]]) {
// the number is prime
P1 *= arr[i];
}
else if (arr[i] != 1 ) {
// the number is non-prime
P2 *= arr[i];
}
}
// Return the absolute difference
return Math.abs(P2 - P1);
}
// Driver Code
public static void main(String []args)
{
int [] arr = new int []{ 1 , 3 , 5 , 10 , 15 , 7 };
int n = arr.length;
// Find the absolute difference
System.out.println(calculateDifference(arr, n));
System.exit( 0 );
}
} // This code is contributed // by Harshit Saini |
# Python3 program to find the Absolute Difference # between the Product of Non-Prime numbers # and Prime numbers of an Array # Function to find the difference between # the product of non-primes and the # product of primes of an array. def calculateDifference(arr, n):
# Find maximum value in the array
max_val = 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.
prime = (max_val + 1 ) * [ True ]
# 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 product of primes in P1 and
# the product of non primes in P2
P1 = 1 ; P2 = 1
for i in range (n):
if prime[arr[i]]:
# the number is prime
P1 * = arr[i]
elif arr[i] ! = 1 :
# the number is non-prime
P2 * = arr[i]
# Return the absolute difference
return abs (P2 - P1)
# Driver Code if __name__ = = '__main__' :
arr = [ 1 , 3 , 5 , 10 , 15 , 7 ]
n = len (arr)
# Find the absolute difference
print (calculateDifference(arr, n))
# This code is contributed # by Harshit Saini |
// C# program to find the Absolute Difference // between the Product of Non-Prime numbers // and Prime numbers of an Array using System;
using System.Linq;
class GFG{
// Function to find the difference between
// the product of non-primes and the
// product of primes of an array.
static int calculateDifference( int []arr, int n)
{
// Find maximum value in the array
int max_val = arr.Max();
// 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.
var prime = Enumerable.Repeat( true ,
max_val+1).ToArray();
// 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 product of primes in P1 and
// the product of non primes in P2
int P1 = 1, P2 = 1;
for ( int i = 0; i < n; i++) {
if (prime[arr[i]]) {
// the number is prime
P1 *= arr[i];
}
else if (arr[i] != 1) {
// the number is non-prime
P2 *= arr[i];
}
}
// Return the absolute difference
return Math.Abs(P2 - P1);
}
// Driver Code
public static void Main()
{
int [] arr = new int []{ 1, 3, 5, 10, 15, 7 };
int n = arr.Length;
// Find the absolute difference
Console.WriteLine(calculateDifference(arr, n));
}
} // This code is contributed // by Harshit Saini |
<?php // PHP program to find the Absolute Difference // between the Product of Non-Prime numbers // and Prime numbers of an Array // Function to find the difference between // the product of non-primes and the // product of primes of an array. function calculateDifference( $arr , $n ){
// Find maximum value in the array
$max_val = 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.
$prime = array_fill (0 , $max_val ,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 product of primes in P1 and
// the product of non primes in P2
$P1 = 1;
$P2 = 1;
for ( $i = 0; $i < $n ; $i ++) {
if ( $prime [ $arr [ $i ]]) {
// the number is prime
$P1 *= $arr [ $i ];
}
else if ( $arr [ $i ] != 1) {
// the number is non-prime
$P2 *= $arr [ $i ];
}
}
// Return the absolute difference
return abs ( $P2 - $P1 );
} // Driver Code $arr = array ( 1, 3, 5, 10, 15, 7 );
$n = count ( $arr , COUNT_NORMAL);
// Find the absolute difference echo CalculateDifference( $arr , $n );
// This code is contributed // by Harshit Saini ?> |
<script> // Javascript program to find the Absolute Difference // between the Product of Non-Prime numbers // and Prime numbers of an Array // Function to find the difference between
// the product of non-primes and the
// product of primes of an array.
function calculateDifference(arr , n)
{
// Find maximum value in the array
var max_val = Math.max.apply(Math,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.
var prime = Array(max_val + 1).fill( 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 product of primes in P1 and
// the product of non primes in P2
var P1 = 1, P2 = 1;
for (i = 0; i < n; i++) {
if (prime[arr[i]]) {
// the number is prime
P1 *= arr[i];
} else if (arr[i] != 1) {
// the number is non-prime
P2 *= arr[i];
}
}
// Return the absolute difference
return Math.abs(P2 - P1);
}
// Driver Code
var arr = [ 1, 3, 5, 10, 15, 7 ];
var n = arr.length;
// Find the absolute difference
document.write(calculateDifference(arr, n));
// This code contributed by gauravrajput1 </script> |
45
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.