

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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)
- Related Questions & Answers
- Print all triplets in sorted array that form AP in C++
- Find the missing number in Geometric Progression in C++
- C program to compute geometric progression
- How to create geometric progression series in R?
- Return numbers spaced evenly on a geometric progression in Numpy
- Find all triplets with zero sum in C++
- C Program for N-th term of Geometric Progression series
- All unique triplets that sum up to a given value in C++
- How to find all unique triplets that adds up to sum Zero using C#?
- Find the element that appears once in sorted array - JavaScript
- Find all triplets in a list with given sum in Python
- Find a subset with greatest geometric mean in C++
- Return numbers spaced evenly on a geometric progression but with negative inputs in Numpy
- Return numbers spaced evenly on a geometric progression but with complex inputs in Numpy
- Find Minimum in Rotated Sorted Array in C++
Advertisements