Java 中的等比数列的第 N 项

10 Sept 2024 | 4 分钟阅读

给定三个数字。第一个数字是等比数列的首项。第二个数字是等比数列的公比,第三个数字是要计算的第 N 项。

示例 1

输入

int a1 = 5, // 首项

int a2 = 3 // 公比

int a3 = 4 // 要找的第 4 项

输出:第四项是 135。

解释:在等比数列中,我们将当前项乘以公比来计算下一项。所以,如果第一项是当前项,那么第二项将是

secondTerm = a1 x a2 = 5 x 3 = 15,使用第二项,我们可以计算第三项,依此类推。

thirdTerm = secondTerm x common ratio = 15 x 3 = 45

fourthTem = thirdTerm x common ratio = 45 x 3 = 135

因此,我们得到第四项为 135。

示例 2

输入

int a1 = 2, // 首项

int a2 = 4 // 公比

int a3 = 3 // 要找的第 3 项

输出:第四项是 32。

方法:暴力法

概念是使用等比数列的第 N 项的数学公式 = a x r(n - 1)。r(n - 1) 的值

文件名:NthGPTerm.java

输出

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

复杂度分析:由于使用 while 循环来计算 r(n - 1) 的值,因此程序的时间复杂度为 O(n),其中 n 是需要计算的项。程序的空间复杂度为 O(1),因为程序不使用额外的空间。

我们可以进一步优化以减少计算 r(n - 1) 值所需的计算时间。

方法:使用递归(优化)

方法

文件名:NthGPTerm.java

输出

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

复杂度分析:递归会进行 log(n) 次。因此,程序的时间复杂度为 O(log(n))。由于递归之后的语句在堆栈中并且稍后计算,因此程序的空间复杂度为 O(log(n)),其中 n 是给定等比数列要计算的项数。