Given an array, arr[] of size N, the task is to print the GCD of all subarrays of size K.
Examples:
Input: arr[] = {2, 4, 3, 9, 14, 20, 25, 17}, K = 2
Output: 2 1 3 1 2 5 1
Explanation:
gcd(2, 4}) = 2
gcd(4, 3) = 1
gcd(3, 9) = 3
gcd(9, 14) = 1
gcd(14, 20) = 2
gcd(20, 25) = 5
gcd(25, 17) = 1
Therefore, the required output is {2, 1, 3, 1, 2, 5, 1}Input: arr[] = {2, 4, 8, 24, 14, 20, 25, 35, 7, 49, 7}, K = 3
Output: 2 4 2 2 1 5 1 7 7
Approach: The idea is to generate all subarrays of size K and print the GCD of each subarray. To efficiently compute the GCD of each subarray, the idea is to use the following property of GCD.
GCD(A1, A2, A3, …, AK) = GCD(A1, GCD(A2, A3, A4, …., AK))
Follow the steps below to solve the problem:
- Initialize a variable, say gcd, to store the GCD of the current subarray.
- Generate K-length subarrays from the given array.
- Applying the above property of GCD, compute the GCD of each subarray, and print the obtained result.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to print the gcd// of each subarray of length Kvoid printSub(int arr[], int N,              int K){    for (int i = 0; i <= N - K; i++) {Â
        // Store GCD of subarray        int gcd = arr[i];Â
        for (int j = i + 1; j < i + K;             j++) {Â
            // Update GCD of subarray            gcd = __gcd(gcd, arr[j]);        }Â
        // Print GCD of subarray        cout << gcd << " ";    }}Â
// Driver Codeint main(){    int arr[] = { 2, 4, 3, 9, 14,                  20, 25, 17 };    int K = 2;    int N = sizeof(arr)            / sizeof(arr[0]);Â
    printSub(arr, N, K);} |
Java
// Java program to implement// the above approachclass GFG{Â
static int __gcd(int a, int b){  if (b == 0)    return a;  return __gcd(b, a % b);}   // Function to print the gcd// of each subarray of length Kstatic void printSub(int arr[],                      int N, int K){  for (int i = 0; i <= N - K; i++)   {    // Store GCD of subarray    int gcd = arr[i];Â
    for (int j = i + 1; j < i + K; j++)     {      // Update GCD of subarray      gcd = __gcd(gcd, arr[j]);    }Â
    // Print GCD of subarray    System.out.print(gcd + " ");  }}Â
// Driver Codepublic static void main(String[] args){Â Â int arr[] = {2, 4, 3, 9, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 14, 20, 25, 17};Â Â int K = 2;Â Â int N = arr.length;Â Â printSub(arr, N, K);}}Â
// This code is contributed by Chitranayal |
Python3
# Python3 program to implement# the above approachfrom math import gcdÂ
# Function to print the gcd# of each subarray of length Kdef printSub(arr, N, K):Â Â Â Â Â Â Â Â Â for i in range(N - K + 1):Â
        # Store GCD of subarray        g = arr[i]Â
        for j in range(i + 1, i + K):                         # Update GCD of subarray            g = gcd(g, arr[j])Â
        # Print GCD of subarray        print(g, end = " ")Â
# Driver Codeif __name__ == '__main__':         arr = [ 2, 4, 3, 9, 14,            20, 25, 17 ]    K = 2    N = len(arr)Â
    printSub(arr, N, K)Â
# This code is contributed by mohit kumar 29 |
C#
// C# program to implement// the above approachusing System;class GFG{Â
static int __gcd(int a, int b){  if (b == 0)    return a;  return __gcd(b, a % b);}   // Function to print the gcd// of each subarray of length Kstatic void printSub(int []arr,                      int N, int K){  for (int i = 0; i <= N - K; i++)   {    // Store GCD of subarray    int gcd = arr[i];Â
    for (int j = i + 1; j < i + K; j++)     {      // Update GCD of subarray      gcd = __gcd(gcd, arr[j]);    }Â
    // Print GCD of subarray    Console.Write(gcd + " ");  }}Â
// Driver Codepublic static void Main(String[] args){Â Â int []arr = {2, 4, 3, 9, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 14, 20, 25, 17};Â Â int K = 2;Â Â int N = arr.Length;Â Â printSub(arr, N, K);}}Â
Â
// This code is contributed by Princi Singh |
Javascript
<script>Â
// Javascript program to implement// the above approach   function __gcd(a, b){  if (b == 0)    return a;  return __gcd(b, a % b);}    // Function to print the gcd// of each subarray of length Kfunction prletSub(arr, N, K){  for (let i = 0; i <= N - K; i++)  {    // Store GCD of subarray    let gcd = arr[i];      for (let j = i + 1; j < i + K; j++)    {      // Update GCD of subarray      gcd = __gcd(gcd, arr[j]);    }      // Print GCD of subarray    document.write(gcd + " ");  }}Â
Â
// Driver CodeÂ
    let arr = [2, 4, 3, 9,               14, 20, 25, 17];  let K = 2;  let N = arr.length;  prletSub(arr, N, K);Â
// This code is contributed by avijitmondal1998.</script> |
2 1 3 1 2 5 1
Â
Time Complexity: O((N – K + 1) * K)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Read More to that Topic: geeksforgeeks.org/gcd-of-all-subarrays-of-size-k/ […]
… [Trackback]
[…] Read More Info here to that Topic: geeksforgeeks.org/gcd-of-all-subarrays-of-size-k/ […]
… [Trackback]
[…] Info to that Topic: geeksforgeeks.org/gcd-of-all-subarrays-of-size-k/ […]