Count of numbers upto M divisible by given Prime Numbers
Last Updated :
16 Dec, 2022
Given an array arr[] of Prime Numbers and a number M, the task is to count the number of elements in the range [1, M] that are divisible by any of the given prime numbers.
Examples:
Input: arr[] = {2, 3, 5, 7} M = 100
Output: 78
Explanation:
In total there are 78 numbers that are divisible by either of 2 3 5 or 7.
Input: arr[] = {2, 5, 7, 11} M = 200
Output: 137
Explanation:
In total there are 137 numbers that are divisible by either of 2 5 7 or 11.
Naive Approach: The idea is iterate over the range [1, M] and check if any of the array element is divides the element in the range [1, M] then count the element else check for the next number in the range.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int count( int a[], int M, int N)
{
int cnt = 0;
for ( int i = 1; i <= M; i++) {
for ( int j = 0; j < N; j++) {
if (i % a[j] == 0) {
cnt++;
break ;
}
}
}
return cnt;
}
int main()
{
int arr[] = { 2, 3, 5, 7 };
int m = 100;
int n = sizeof (arr) / sizeof (arr[0]);
cout << count(arr, m, n);
return 0;
}
|
Java
import java.io.*;
public class GFG{
static int count( int a[], int M, int N)
{
int cnt = 0 ;
for ( int i = 1 ; i <= M; i++)
{
for ( int j = 0 ; j < N; j++)
{
if (i % a[j] == 0 )
{
cnt++;
break ;
}
}
}
return cnt;
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 5 , 7 };
int m = 100 ;
int n = arr.length;
System.out.print(count(arr, m, n));
}
}
|
Python3
def count(a, M, N):
cnt = 0
for i in range ( 1 , M + 1 ):
for j in range (N):
if (i % a[j] = = 0 ):
cnt + = 1
break
return cnt
lst = [ 2 , 3 , 5 , 7 ]
m = 100
n = len (lst)
print (count(lst, m, n))
|
C#
using System;
class GFG{
static int count( int []a, int M, int N)
{
int cnt = 0;
for ( int i = 1; i <= M; i++)
{
for ( int j = 0; j < N; j++)
{
if (i % a[j] == 0)
{
cnt++;
break ;
}
}
}
return cnt;
}
public static void Main(String[] args)
{
int []arr = { 2, 3, 5, 7 };
int m = 100;
int n = arr.Length;
Console.Write(count(arr, m, n));
}
}
|
Javascript
<script>
function count(a, M, N)
{
let cnt = 0;
for (let i = 1; i <= M; i++) {
for (let j = 0; j < N; j++) {
if (i % a[j] == 0) {
cnt++;
break ;
}
}
}
return cnt;
}
let arr = [ 2, 3, 5, 7 ];
let m = 100;
let n = arr.length;
document.write(count(arr, m, n));
</script>
|
Time Complexity: O(N*M)
Auxiliary Space: O(1)
Another Approach: Another method to solve this problem is use Dynamic Programming and Sieve. Mark all the numbers up to M that are divisible by any prime number in the array. Then count all the marked numbers and print it.
Share your thoughts in the comments
Please Login to comment...