Longest subarray in which all elements are a factor of K | C ++ program to implement the above approach ; Function to find the length of the longest subarray in which all elements are a factor of K ; Stores length of the longest subarray in which all elements are a factor of K ; Stores length of the current subarray ; Traverse the array arr [ ] ; If A [ i ] is a factor of K ; Update Len ; Update MaxLen ; If A [ i ] is not a factor of K ; Update Len ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_longest_subarray ( int A [ ] , int N , int K ) { int MaxLen = 0 ; int Len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( K % A [ i ] == 0 ) { Len ++ ; MaxLen = max ( MaxLen , Len ) ; } else { Len = 0 ; } } return MaxLen ; } int main ( ) { int A [ ] = { 2 , 8 , 3 , 10 , 6 , 7 , 4 , 9 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; ; int K = 60 ; cout << find_longest_subarray ( A , N , K ) ; return 0 ; }