Count of elements in given Array divisible by all elements in their prefix - GeeksforGeeks

24 Jan, 2022
Given an array arr[] containing N positive integers, the task is to find the total number of elements in the array that are divisible by all the elements present before them.
Examples:
Input: arr[] = {10, 6, 60, 120, 30, 360}Output: 3Explanation: 60, 120 and 360 are the required elements.
Input: arr[] = {2, 6, 5, 60}Output: 2Explanation: 6 and 60 are the elements.
Approach: As known, that any number X is divided by {X1, X2, X3, X4, . . ., Xn}, if X is divided by LCM of {X1, X2, X3, X4, ..., Xn). And LCM of any number A, B is [(A*B)/gcd(A, B)]. Now to solve this problem, follow the below steps:
Create a variable ans which stores the final answer and initialize it with 0.Create another variable lcm which stores LCM up to the ith element while iterating through the array. Initialize lcm with arr[0].Iterate over the array from i = 1 to i = N, and in each iteration, check if arr[i] is divided by lcm. If yes increment ans by 1. Also, update lcm with lcm up to ith element.Print ans as the final answer to this problem.
Create a variable ans which stores the final answer and initialize it with 0.
Create another variable lcm which stores LCM up to the ith element while iterating through the array. Initialize lcm with arr[0].
Iterate over the array from i = 1 to i = N, and in each iteration, check if arr[i] is divided by lcm. If yes increment ans by 1. Also, update lcm with lcm up to ith element.
Print ans as the final answer to this problem.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to return total number of// elements which are divisible by// all their previous elementsint countElements(int arr[], int N){    int ans = 0;    int lcm = arr[0];    for (int i = 1; i < N; i++) {         // To check if number is divisible        // by lcm of all previous elements        if (arr[i] % lcm == 0) {            ans++;        }         // Updating LCM        lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]);    }    return ans;} // Driver codeint main(){    int arr[] = { 10, 6, 60, 120, 30, 360 };     int N = sizeof(arr) / sizeof(int);    cout << countElements(arr, N);    return 0;}
// Java program for the above approachimport java.util.*;public class GFG {   // Recursive function to return gcd of a and b  static int __gcd(int a, int b)  {     // Everything divides 0    if (a == 0)      return b;    if (b == 0)      return a;     // base case    if (a == b)      return a;     // a is greater    if (a > b)      return __gcd(a - b, b);    return __gcd(a, b - a);  }   // Function to return total number of  // elements which are divisible by  // all their previous elements  static int countElements(int arr[], int N)  {    int ans = 0;    int lcm = arr[0];    for (int i = 1; i < N; i++) {       // To check if number is divisible      // by lcm of all previous elements      if (arr[i] % lcm == 0) {        ans++;      }       // Updating LCM      lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]);    }    return ans;  }   public static void main(String args[])  {    int arr[] = { 10, 6, 60, 120, 30, 360 };    int N = arr.length;    System.out.print(countElements(arr, N));  }} // This code is contributed by Samim Hossain Mondal.
# Python code for the above approach # Recursive function to return gcd of a and bdef __gcd(a, b):       # Everything divides 0    if (a == 0):        return b;    if (b == 0):        return a;     # base case    if (a == b):        return a;     # a is greater    if (a > b):        return __gcd(a - b, b);    return __gcd(a, b - a); # Function to return total number of# elements which are divisible by# all their previous elementsdef countElements(arr, N):    ans = 0;    lcm = arr[0];    for i in range(1, N):         # To check if number is divisible        # by lcm of all previous elements        if (arr[i] % lcm == 0):            ans += 1         # Updating LCM        lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]);    return ans; # Driver codearr = [10, 6, 60, 120, 30, 360]; N = len(arr)print(countElements(arr, N)); # This code is contributed by Saurabh Jaiswal
// C#program for the above approachusing System; public class GFG {   // Recursive function to return gcd of a and b  static int __gcd(int a, int b)  {     // Everything divides 0    if (a == 0)      return b;    if (b == 0)      return a;     // base case    if (a == b)      return a;     // a is greater    if (a > b)      return __gcd(a - b, b);    return __gcd(a, b - a);  }   // Function to return total number of  // elements which are divisible by  // all their previous elements  static int countElements(int[] arr, int N)  {    int ans = 0;    int lcm = arr[0];    for (int i = 1; i < N; i++) {       // To check if number is divisible      // by lcm of all previous elements      if (arr[i] % lcm == 0) {        ans++;      }       // Updating LCM      lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]);    }    return ans;  }   public static void Main()  {    int[] arr = { 10, 6, 60, 120, 30, 360 };    int N = arr.Length;    Console.Write(countElements(arr, N));  }} // This code is contributed by ukasp.
<script>      // JavaScript code for the above approach       // Recursive function to return gcd of a and b      function __gcd(a, b) {          // Everything divides 0          if (a == 0)              return b;          if (b == 0)              return a;           // base case          if (a == b)              return a;           // a is greater          if (a > b)              return __gcd(a - b, b);          return __gcd(a, b - a);      }        // Function to return total number of      // elements which are divisible by      // all their previous elements      function countElements(arr, N) {          let ans = 0;          let lcm = arr[0];          for (let i = 1; i < N; i++) {               // To check if number is divisible              // by lcm of all previous elements              if (arr[i] % lcm == 0) {                  ans++;              }               // Updating LCM              lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]);          }          return ans;      }       // Driver code       let arr = [10, 6, 60, 120, 30, 360];       let N = arr.length      document.write(countElements(arr, N)); // This code is contributed by Potta Lokesh  </script>
  
3
 
Time complexity: O(N * logD) where D is the maximum array elementAuxiliary Space: O(N)
 
lokeshpotta20
_saurabh_jaiswal
samim2000
ukasp
GCD-LCM
prefix
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Building Heap from Array
Move all negative numbers to beginning and positive to end with constant extra space
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7