Find all triplets in a sorted array that forms Geometric Progression in C++


Suppose we have a sorted array with distinct positive integers. We have to find all triplets, that forms Geometric progression with integral common ratio. Suppose the array elements are [1, 2, 6, 10, 18, 54], The triplets are (2, 6, 18), and (6, 18, 54), these are forming geometric progression.

To solve this, we will start from the second element, and fix every element as middle element, and search for the lesser and greater elements. For middle element arr[j] to be middle of geometric progression, the previous element arr[i] and arr[k] will be like

$$\frac{arr[j]}{arr[i]}=\frac{arr[k]}{arr[j]}=rš‘Ÿ$$

Example

#include<iostream>
using namespace std;
void getTriplets(int arr[], int n) {
   for (int j = 1; j < n - 1; j++) {
      int i = j - 1, k = j + 1;
      while (i >= 0 && k <= n - 1) {
         while (arr[j] % arr[i] == 0 && arr[k] % arr[j] == 0 && arr[j] / arr[i] == arr[k] / arr[j]) {
            cout << "("<< arr[i] << ", " << arr[j] << ", " << arr[k] << ")" << endl;
               k++;
               i--;
         }
         if(arr[j] % arr[i] == 0 && arr[k] % arr[j] == 0) {
            if(arr[j] / arr[i] < arr[k] / arr[j])
               i--;
         else
            k++;
         }else if (arr[j] % arr[i] == 0)
            k++;
         else
            i--;
      }
   }
}
int main() {
   int arr[] = {1, 2, 6, 10, 18, 54};
   int n = sizeof(arr) / sizeof(arr[0]);
   getTriplets(arr, n);
}

Output

(2, 6, 18)
(6, 18, 54)

Updated on: 01-Nov-2019

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements