Product of all the elements in an array divisible by a given number K
Last Updated :
05 Sep, 2022
Given an array containing N elements and a number K. The task is to find the product of all such elements of the array which are divisible by K.
Examples:
Input : arr[] = {15, 16, 10, 9, 6, 7, 17}
K = 3
Output : 810
Input : arr[] = {5, 3, 6, 8, 4, 1, 2, 9}
K = 2
Output : 384
The idea is to traverse the array and check the elements one by one. If an element is divisible by K then multiply that element’s value with the product so far and continue this process while the end of the array is reached.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int findProduct( int arr[], int n, int k)
{
int prod = 1;
for ( int i = 0; i < n; i++) {
if (arr[i] % k == 0) {
prod *= arr[i];
}
}
return prod;
}
int main()
{
int arr[] = { 15, 16, 10, 9, 6, 7, 17 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
cout << findProduct(arr, n, k);
return 0;
}
|
C
#include <stdio.h>
int findProduct( int arr[], int n, int k)
{
int prod = 1;
for ( int i = 0; i < n; i++) {
if (arr[i] % k == 0) {
prod *= arr[i];
}
}
return prod;
}
int main()
{
int arr[] = { 15, 16, 10, 9, 6, 7, 17 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
printf ( "%d" ,findProduct(arr, n, k));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int findProduct( int arr[], int n, int k)
{
int prod = 1 ;
for ( int i = 0 ; i < n; i++) {
if (arr[i] % k == 0 ) {
prod *= arr[i];
}
}
return prod;
}
public static void main (String[] args) {
int arr[] = { 15 , 16 , 10 , 9 , 6 , 7 , 17 };
int n = arr.length;
int k = 3 ;
System.out.println(findProduct(arr, n, k));
}
}
|
Python3
def findProduct(arr, n, k):
prod = 1
for i in range (n):
if (arr[i] % k = = 0 ):
prod * = arr[i]
return prod
if __name__ = = "__main__" :
arr = [ 15 , 16 , 10 , 9 , 6 , 7 , 17 ]
n = len (arr)
k = 3
print (findProduct(arr, n, k))
|
C#
using System;
class GFG
{
static int findProduct( int []arr, int n, int k)
{
int prod = 1;
for ( int i = 0; i < n; i++)
{
if (arr[i] % k == 0)
{
prod *= arr[i];
}
}
return prod;
}
public static void Main()
{
int []arr = { 15, 16, 10, 9, 6, 7, 17 };
int n = arr.Length;
int k = 3;
Console.WriteLine(findProduct(arr, n, k));
}
}
|
PHP
<?php
function findProduct(& $arr , $n , $k )
{
$prod = 1;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $arr [ $i ] % $k == 0)
{
$prod *= $arr [ $i ];
}
}
return $prod ;
}
$arr = array (15, 16, 10, 9, 6, 7, 17 );
$n = sizeof( $arr );
$k = 3;
echo (findProduct( $arr , $n , $k ));
?>
|
Javascript
<script>
function findProduct( arr, n, k)
{
var prod = 1;
for ( var i = 0; i < n; i++) {
if (arr[i] % k == 0) {
prod *= arr[i];
}
}
return prod;
}
var arr = [15, 16, 10, 9, 6, 7, 17 ];
document.write(findProduct(arr, 7, 3));
</script>
|
Complexity Analysis:
- Time Complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...