Find N Geometric Means between A and B using C++.


Suppose we have three integers A, B and N. We have to find N geometric means between A and B. If A = 2, B = 32, and N = 3, then the output will be 4, 8, 16

The task is simple we have to insert N number of elements in the geometric Progression where A and B are the first and last term of that sequence. Suppose G1, G2, …. Gn are n geometric means. So the sequence will be A, G1, G2, …. Gn, B. So B is the (N + 2)th term of the sequence. So we can use these formulae −

$$B=A*R^{N+1}$$

$$R^{N+1}=\frac{B}{A}$$

$$R=\lgroup \frac{B}{A}\rgroup^{\frac{1}{N+1}}$$

Example

 Live Demo

#include<iostream>
#include<cmath>
using namespace std;
void showMeans(int A, int B, int N) {
   float R = (float)pow(float(B / A), 1.0 / (float)(N + 1));
   for (int i = 1; i <= N; i++)
   cout << (A * pow(R, i)) <<" ";
}
int main() {
   int A = 3, B = 81, N = 2;
   showMeans(A, B, N);
}

Output

9 27

Updated on: 30-Oct-2019

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements