It has been sometime since I got myself to solve mathematical equations. So I can't seem to find a way to come to a simplified equation for finding the common ratio knowing the final sum and the value of n in the formula :
$$\text{finalSum} = r(1 - r^n)/(1 - r)$$
For example: 3, 9, 27, 81, 243
$$363 = r(1 - r^5)/(1 - r)$$
Given above is a very simple example. But I'll be dealing these in decimals. Is there any way of getting a simplified equation to get the value of r? Or is the method of substitution the only way?
PS: This is for a program I'm writing
Please let me know.
Thanks
This is binary search based solution for program.
As $r$ is always a positive integer. You can start with say $r=1$ and than calculate the sum using, $$ S = \frac{r(1 - r^n)}{(1 - r)} $$ Let the given sum is $A$. You can than check if $A \geq S$, if yes than double the $r$.
Say, currently $r = 2^k$ for which $A \geq S$ and at $r=2^{k+1}$, $A \leq S$.
Then you know answer lies between $2^k$ and $2^{k+1}$. You can apply binary search on these values to find $r$ for which $A=S$.
Sum at each iteration can be calculated in $O(log(n))$. So, final Time Complexity for this will be $O(log(r')*log(n))$ (where $r'$ is the answer).
Note: This will always give exact $r$.
Ref:
Binary Search
Calculate power in log(n) time