GFG App
Open App
Browser
Continue

# Count of elements in given Array divisible by all elements in their prefix

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: 3
Explanation: 60, 120 and 360 are the required elements.

Input: arr[] = {2, 6, 5, 60}
Output: 2
Explanation: 6 and 60 are the elements.

Brute Force/ Naive Approach:

The brute force approach to solving the problem of Count of elements in given Array divisible by all elements in their prefix would be to check each element of the array one by one and calculate if it’s divisible by all its previous elements.

Steps to implement the approach:

• Initialize a variable ans to 0 to count the number of elements that satisfy the condition.
• Traverse the array from index 1 to N-1.
• For each index i, traverse the array from index 0 to i-1 to check if the element is divisible by all its previous elements.
• If the element is divisible by all its previous elements, increment the ans variable.
• Return the ans variable as the final count.

Below is the implementation of the approach:

## C++

 #include using namespace std;   // Function to return total number of // elements which are divisible by // all their previous elements int countElements(int arr[], int N) {     int ans = 0; // Initialize the count of elements to zero     for (int i = 1; i < N;          i++) { // Traverse the array from index 1 to N-1         bool is_divisible             = true; // Initialize the flag to true         for (int j = 0; j < i; j++) { // Traverse the array                                       // from index 0 to i-1             if (arr[i] % arr[j]                 != 0) { // Check if the i-th element is not                         // divisible by any of the previous                         // elements                 is_divisible                     = false; // Set the flag to false                 break; // Break out of the inner loop             }         }         if (is_divisible) { // If the i-th element is                             // divisible by all its previous                             // elements             ans++; // Increment the count of elements         }     }     return ans; // Return the count of elements that are                 // divisible by all their previous elements }   // Driver code int main() {     int arr[] = {         10, 6, 60, 120, 30, 360     }; // Initialize the input array       int N         = sizeof(arr)           / sizeof(               int); // Calculate the size of the input array     cout << countElements(         arr, N); // Call the countElements() function and                  // print the result     return 0; }

## Java

 import java.util.*;   public class Main {     // 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; // Initialize the count of elements to zero         for (int i = 1; i < N; i++) { // Traverse the array                                       // from index 1 to N-1             boolean is_divisible                 = true; // Initialize the flag to true             for (int j = 0; j < i;                  j++) { // Traverse the array from index 0                         // to i-1                 if (arr[i] % arr[j]                     != 0) { // Check if the i-th element is                             // not divisible by any of the                             // previous elements                     is_divisible                         = false; // Set the flag to false                     break; // Break out of the inner loop                 }             }             if (is_divisible) { // If the i-th element is                                 // divisible by all its                                 // previous elements                 ans++; // Increment the count of elements             }         }         return ans; // Return the count of elements that are                     // divisible by all their previous                     // elements     }       // Driver code     public static void main(String[] args)     {         int[] arr = {             10, 6, 60, 120, 30, 360         }; // Initialize the input array           int N = arr.length; // Calculate the size of the                             // input array         System.out.println(countElements(             arr, N)); // Call the countElements() function                       // and print the result     } }

## Python3

 def count_elements(arr):     ans = 0  # Initialize the count of elements to zero     N = len(arr)  # Calculate the size of the input array     for i in range(1, N):  # Traverse the array from index 1 to N-1         is_divisible = True  # Initialize the flag to true         for j in range(i):  # Traverse the array from index 0 to i-1             if arr[i] % arr[j] != 0:  # Check if the i-th element is not divisible by any of the previous elements                 is_divisible = False  # Set the flag to false                 break  # Break out of the inner loop         if is_divisible:  # If the i-th element is divisible by all its previous elements             ans += 1  # Increment the count of elements     return ans  # Return the count of elements that are divisible by all their previous elements   # Driver code arr = [10, 6, 60, 120, 30, 360]  # Initialize the input array print(count_elements(arr))  # Call the count_elements() function and print the result

## C#

 // C# program to count the number of elements which are // divisible by all their previous elements. using System;   class MainClass {       // 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; // Initialize the count of elements to zero     for (int i = 1; i < N; i++) { // Traverse the array       // from index 1 to N-1       bool is_divisible         = true; // Initialize the flag to true       for (int j = 0; j < i;            j++) { // Traverse the array from index 0         // to i-1         if (arr[i] % arr[j]             != 0) { // Check if the i-th element is           // not divisible by any of the           // previous elements           is_divisible             = false; // Set the flag to false           break; // Break out of the inner loop         }       }       if (is_divisible) { // If the i-th element is         // divisible by all its         // previous elements         ans++; // Increment the count of elements       }     }     return ans; // Return the count of elements that are     // divisible by all their previous     // elements   }     // Driver code   public static void Main()   {     int[] arr = {       10, 6, 60, 120, 30, 360       }; // Initialize the input array       int N = arr.Length; // Calculate the size of the     // input array     Console.WriteLine(countElements(       arr, N)); // Call the countElements() function     // and print the result   } }

## Javascript

 // Function to return total number of // elements which are divisible by // all their previous elements function countElements(arr, N) {     let ans = 0;// Initialize the count of elements to zero           // Traverse the array     // from index 1 to N-1     for (let i = 1; i < N; i++) {         let is_divisible = true; // Initialize the flag to true                       // Traverse the array from index 0             // to i-1             for (let j = 0; j < i; j++) {                                   // Check if the i-th element is                 // not divisible by any of the                 // previous elements                 if (arr[i] % arr[j] !== 0) {                     is_divisible = false; // Set the flag to false                     break; // Break out of the inner loop                 }             }                   // If the i-th element is         // divisible by all its         // previous elements         if (is_divisible) {         ans++;// Increment the count of elements         }     }     // Return the count of elements that are     // divisible by all their previous     // elements     return ans; }   // Usage let arr = [10, 6, 60, 120, 30, 360]; let N = arr.length; console.log(countElements(arr, N)); // Output: count of elements that are divisible by all previous elements in the array   // This code is contributed by shivhack999

Output

3

Time Complexity: O(N2 )
Space Complexity: O(1)

Another 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:

1. Create a variable ans which stores the final answer and initializes it with 0.
2. Create another variable lcm which stores LCM up to the ith element while iterating through the array. Initialize lcm with arr[0].
3. 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.
4. Print ans as the final answer to this problem.

Below is the implementation of the above approach:

## C++

 // C++ code to implement the above approach #include using namespace std;   // Function to return total number of // elements which are divisible by // all their previous elements 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; }   // Driver code int main() {     int arr[] = { 10, 6, 60, 120, 30, 360 };       int N = sizeof(arr) / sizeof(int);     cout << countElements(arr, N);     return 0; }

## Java

 // Java program for the above approach import 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.

## Python3

 # Python code for the above approach   # Recursive function to return gcd of a and b def __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 def 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 code arr = [10, 6, 60, 120, 30, 360];   N = len(arr) print(countElements(arr, N));   # This code is contributed by Saurabh Jaiswal

## C#

 // C#program for the above approach using 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.

## Javascript



Output

3

Time complexity: O(N * logD) where D is the maximum array element
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up