1.题目描述
2.思路
(1) gad(A,B)代表最大公约数
gcd(f(n),f(m))=f(gcd(n,m))
(2)用递归求最大公约数
static int gcd(int n ,int m)
{
if(n%m==0)
{
return m;//递归出口
}
return gcd(m,n%m);//辗转相除法
}
(3)用递归求斐波那契数列
//某项等于前两项的和
static int Fab(int n)
{
if(n==1||n==2)
{ return 1;}
return Fab(n-1)+Fab(n-2);
}
Java中有两个类BigInteger和BigDecimal分别表示大整数类和大浮点数类,这两个类都在java.math.*包中
常用的一些函数
(1)add(); 大整数相加
BigInteger a=new BigInteger(“23”);
BigInteger b=new BigInteger(“34”);
a. add(b);
(2)pow(); a.pow(b)=a^b
(3)gcd(); 最大公约数
(4)abs(); 绝对值
(5)基本常量:
A=BigInteger.ONE 1
B=BigInteger.TEN 10
C=BigInteger.ZERO 0
3.代码实现
package 蓝桥杯;
import java.math.BigInteger;
public class 斐波那契数列 {
public static void main(String[] args) {
// TODO Auto-generated method stub
BigInteger num1=Fab(2020);//斐波那契数列第2020项
BigInteger num2=Fab(520);//斐波那契数列第520项
System.out.println(num1.gcd(num2));
}
public static BigInteger Fab(int n)//记得加static ,静态的全局变量
{
BigInteger first=BigInteger.ONE;//1
BigInteger second=BigInteger.ONE;//2
BigInteger third=null;
if(n==1||n==2)
{
return first;
}
for(int i=3;i<=n;i++)
{
//新的两项是前两项之和
third=first.add(second);
//后移
first=second;
second=third;
}
return third;
}
}