
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Product of All Composite Numbers in an Array in C++
Given an array arr[n] of n number of integers, the task is to find the product of all composite numbers in an array.
Composite numbers are the whole numbers which are made by multiplying 2 other whole numbers. For example 6 is a composite number which can be made by multiplying 2 and 3 which are whole numbers. Also we can say they are not prime.
Input
arr[] = {1, 2, 4, 5, 6, 7}
Output
24
Explanation − the composite numbers in the array are 4 and 6 and their product is 24.
Input
arr[] = {10, 2, 4, 5, 6, 11}
Output
240
Explanation − the composite numbers in the array are 10, 4, 6 and their Product is 240.
Approach used below is as follows to solve the problem
Iterate every element of an array.
Find for the non-prime or composite numbers, i.e. divisible by some other number except 1.
Multiply all the composite numbers.
Return the result.
Algorithm
Start Step 1→ Declare function to find the product of consecutive numbers in array int product_arr(int arr[], int size) declare int max = *max_element(arr, arr + size) set vector<bool> prime(max + 1, true) set prime[0] = true set prime[1] = true Loop For int i = 2 and i * i <= max and i++ IF (prime[i] == true) Loop For int j = i * 2 and j <= max and j += i Set prime[j] = false End End End Set int product = 1 Loop For int i = 0 and i < size and i++ IF (!prime[arr[i]]) Set product *= arr[i] End End return product Stop
Example
#include <bits/stdc++.h> using namespace std; //function to find product of consecutive numbers in an array int product_arr(int arr[], int size){ int max = *max_element(arr, arr + size); vector<bool> prime(max + 1, true); prime[0] = true; prime[1] = true; for (int i = 2; i * i <= max; i++){ if (prime[i] == true){ for (int j = i * 2; j <= max; j += i) prime[j] = false; } } int product = 1; for (int i = 0; i < size; i++) if (!prime[arr[i]]){ product *= arr[i]; } return product; } int main(){ int arr[] = { 2, 4, 6, 8, 10}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"product of consecutive numbers in an array: "<<product_arr(arr, size); return 0; }
Output
If run the above code it will generate the following output −
product of consecutive numbers in an array: 1920