Java中如何用公式法求斐波那契数列的前n项和。
Java中如何用公式法求斐波那契数列的前n项和。
公式:sum = (fib(n + 2) - 1)
其中,fib(n)代表第n个斐波那契数,sum代表前n项和。公式的推导过程可以参考数学知识。
以下是使用公式法求斐波那契数列的前n项和的Java代码实现:
import java.math.BigInteger;
public class FibonacciSum {
public static BigInteger fibonacci(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be non-negative");
}
if (n == 0) {
return BigInteger.ZERO;
}
if (n == 1) {
return BigInteger.ONE;
}
BigInteger f0 = BigInteger.ZERO;
BigInteger f1 = BigInteger.ONE;
BigInteger fn = BigInteger.ZERO;
for (int i = 2; i <= n; i++) {
fn = f0.add(f1);
f0 = f1;
f1 = fn;
}
return fn;
}
public static BigInteger fibonacciSum(int n) {
BigInteger fibNPlus2 = fibonacci(n + 2);
BigInteger one = BigInteger.ONE;
return fibNPlus2.subtract(one);
}
public static void main(String[] args) {
int n = 10;
System.out.println("The sum of the first " + n + " Fibonacci numbers is " + fibonacciSum(n));
}
}
在上述代码中,fibonacci方法实现了求解第n个斐波那契数的逻辑。fibonacciSum方法利用公式计算前n项斐波那契数的和。在main方法中,我们打印出前10项斐波那契数的和。需要注意的是,因为斐波那契数列的数值通常很大,所以在Java中可以使用BigInteger来处理。
该回答引用chatgpt:有问题可以@我
package com.test;
public class FibonacciSum {
public static void main(String[] args) {
int n = 10; // 计算前n项的和
int sum = fibSum(n);
System.out.println("斐波那契数列前" + n + "项的和为: " + sum);
}
public static int fibSum(int n) {
if (n <= 0) {
return 0;
}
int sum = 0;
int prev = 0;
int current = 1;
for (int i = 1; i <= n; i++) {
sum += current;
int temp = current;
current = prev + current;
prev = temp;
}
return sum;
}
}
费波那契数列(兔子繁殖数列)
1.定义
https://www.jianshu.com/p/a93eb81fb8a5
2.流程
3.代码
public class Fibonacci {
public static void main(String[] args) {
int fun = fun(5);
System.out.println(fun);
}
public static int fun(int num){
if(num == 1 || num == 2){
return 1;
}
return fun(num-1)+fun(num-2);
}
}