
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 𝑂(√𝑛) amount of time. Then get the product and try to find the absolute difference.
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
#include <iostream> #include <cmath> using namespace std; bool isPrime(int n){ 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); } main() { int arr[] = { 4, 5, 3, 8, 13, 10}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Difference: " << diffPrimeNonPrimeProd(arr, n); }
Output
Difference: 125
- Related Questions & Answers
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Product of all prime numbers in an Array in C++
- Print prime numbers with prime sum of digits in an array
- Find product of prime numbers between 1 to n in C++
- Sum of all prime numbers in an array - JavaScript
- Find the Product of first N Prime Numbers in C++
- XOR of all Prime numbers in an Array in C++
- Sum of prime numbers between a range - JavaScript
- Sum of the first N Prime numbers
- Maximum no. of contiguous Prime Numbers in an array in C++
- Check if product of array containing prime numbers is a perfect square in Python
- C Program to Minimum and Maximum prime numbers in an array
- Prime numbers and Fibonacci in C++
- Sum of all prime numbers in JavaScript
- Python - Find the number of prime numbers within a given range of numbers
Advertisements