N^{th} Term of Geometric Progression in JavaThree numbers are given. The first number is the first term of the geometric progression. The second number is the common ratio of the geometric progression, and the third number is the n^{th} term that has to be computed. Example 1: Input int a1 = 5, // first term int a2 = 3 // common ratio int a3 = 4 // 4^{th} term to be found Output: The fourth term is 135. Explanation: In geometric progression, we multiply the current term with the common ratio to compute the next term. So, if the first term is the current term, then the second term will be: secondTerm = a1 x a2 = 5 x 3 = 15, using the second term we can compute the third term, and so on. thirdTerm = secondTerm x common ratio = 15 x 3 = 45 fourthTem = thirdTerm x common ratio = 45 x 3 = 135 Thus, we get the fourth term as 135. Example 2: Input int a1 = 2, // first term int a2 = 4 // common ratio int a3 = 3 // 3^{rd} term to be found Output: The fourth term is 32. Approach: Brute ForceThe concept is to use the mathematical formula for computing the nth term of the Geometric Progression = a x r^{(n  1)}. The value of r^{(n  1)} FileName: NthGPTerm.java Output: For a geometric progression that has the first term as: 5 and the common ratio as: 3, the 4th term is: 135 For a geometric progression that has the first term as: 2 and the common ratio as: 4, the 3rd term is: 32 Complexity Analysis: Since while loop is used for computing the value of r^{(n  1)}, the time complexity of the program is O(n), where n is the term that needs to be computed. The space complexity of the program is O(1), as no extra space is used by the program. We can do further optimization to reduce the computation time to compute the value of r^{(n  1)}. Approach: Using Recursion (Optimized)The approach FileName: NthGPTerm.java Output: For a geometric progression that has the first term as: 5 and the common ratio as: 3, the 4th term is: 135 For a geometric progression that has the first term as: 2 and the common ratio as: 4, the 3rd term is: 32 Complexity Analysis: The recursion goes till log(n) times. Thus, the time complexity of the program is O(log(n)). Since the statements after the recursion go in the stack and are computed later, the space complexity of the program is O(log(n)), where n is the number of terms to be computed of the given geometric progression.
Next TopicCoding Guidelines in Java
