Check if LCM of array elements is divisible by a prime number or not
Last Updated :
16 Feb, 2023
Given an array and a number k, the task is to find if LCM of the array is divisible by k or not.
Examples :
Input : int[] a = {10, 20, 15, 25}
k = 3
Output : true
Input : int[] a = {24, 21, 45, 57, 36};
k = 23;
Output : false
One simple solution is to first find LCM of array elements, then check if LCM is divisible by k or not.
Here, without calculating the LCM of the number we can find that LCM of the array of number is divisible by a prime number k or not. If any number of the array is divisible by prime number k, then the LCM of the number is also divisible by prime number k.
C++
#include<iostream>
using namespace std;
bool func( int a[], int k, int n)
{
for ( int i = 0; i < n; i++)
if (a[i] % k == 0)
return true ;
return false ;
}
int main()
{
int a[] = {14, 27, 38, 76, 84};
int k = 19;
bool res = func(a, k, 5);
if (res)
cout<< "true" ;
else
cout<< "false" ;
return 0;
}
|
Java
import java.lang.*;
import java.util.*;
class GFG
{
static boolean func( int a[], int k)
{
for ( int i = 0 ; i < a.length; i++)
if (a[i] % k == 0 )
return true ;
return false ;
}
public static void main(String args[])
{
int [] a = { 14 , 27 , 38 , 76 , 84 };
int k = 19 ;
boolean res = func(a, k);
System.out.println(res);
}
}
|
Python 3
def func( a, k, n) :
for i in range ( 0 , n) :
if ( a[i] % k = = 0 ):
return True
a = [ 14 , 27 , 38 , 76 , 84 ]
k = 19
res = func(a, k, 5 )
if (res) :
print ( "true" )
else :
print ( "false" )
|
C#
using System;
class GFG
{
static bool func( int []a, int k)
{
for ( int i = 0; i < a.Length; i++)
if (a[i] % k == 0)
return true ;
return false ;
}
public static void Main()
{
int []a = {14, 27, 38, 76, 84};
int k = 19;
bool res = func(a, k);
Console.Write(res);
}
}
|
PHP
<?php
function func( $a , $k , $n )
{
for ( $i = 0; $i < $n ; $i ++)
if ( $a [ $i ] % $k == 0)
return true;
return false;
}
$a = array (14, 27, 38, 76, 84);
$k = 19;
$res = func( $a , $k , 5);
if ( $res )
echo "true" ;
else
echo "false" ;
?>
|
Javascript
<script>
function func(a , k)
{
for (let i = 0; i < a.length; i++)
if (a[i] % k == 0)
return true ;
return false ;
}
let a = [ 14, 27, 38, 76, 84 ];
var k = 19;
let res = func(a, k);
document.write(res);
</script>
|
Output :
true
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...