Product of all the elements in an array divisible by a given number K in C++


Given an array arr[n] with n number of integers and another integer k, the task is to find the product all the elements of arr[] which are divisible by k.

To solve the problem we have to iterate every element of the array and find whether it is completely divisible by the number k and then product all the elements and store it into a variable. Like we have an array arr[] = {1, 2, 3, 4, 5, 6 } and assuming we have k = 2 so the numbers in the array which are divisible by 2 are 2, 4, 6 and their product will be equal to 48.

So, let's see the example how we want our answers as per the input

Input 

arr[] = {10, 11, 55, 2, 6, 7}
K = 11

Output 

605

Explanation − the numbers divisible by 11 are 11 and 55 only their product is 605

Input 

arr[] = {9, 8, 7, 6, 3}
K = 3

Output 

162

Approach used below is as follows to solve the problem

  • Iterate the whole array till the very end of an array.

  • Look for every integer which is divisible by K.

  • Product every element divisible by K.

  • Return the product.

  • Print the result.

Algorithm

Start
Step 1→ declare function to find all the numbers divisible by number K
   int product(int arr[], int size, int k)
      declare int prod = 1
      Loop For int i = 0 and i < size and i++
      IF (arr[i] % k == 0)
         Set prod *= arr[i]
      End
      End
      return prod
Step 2→ In main()
   Declare int arr[] = {2, 3, 4, 5, 6 }
   Declare int size = sizeof(arr) / sizeof(arr[0])
   Set int k = 2
   Call product(arr, size, k)
Stop

Example

 Live Demo

#include <iostream>
using namespace std;
//function to find elements in an array divisible by k
int product(int arr[], int size, int k){
   int prod = 1;
   for (int i = 0; i < size; i++){
      if (arr[i] % k == 0){
         prod *= arr[i];
      }
   }
   return prod;
}
int main(){
   int arr[] = {2, 3, 4, 5, 6 };
   int size = sizeof(arr) / sizeof(arr[0]);
   int k = 2;
   cout<<"product of elements are : "<<product(arr, size, k);
   return 0;
}

Output

If run the above code it will generate the following output −

product of elements are : 48

Updated on: 13-Aug-2020

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements