
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements