题目求斐波那契数列的第n位数
介绍:
斐波那契数列第一个和第二个数1,其他数是它前两数之和,例如:
1、1、2、3、5、8、13、21、34、……等等
代码如下:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(fbnq(scanner.nextInt()));
}
static int fbnq(int n){
if (n==1||n==2){
return 1;
}else {
return fbnq(n-1) + fbnq(n-2);
}
}
但是如果n=100时我们看看会有什么情况:
这里直接卡住无法返回结果,说明计算的数太大了。
所以我们在这里使用Biginteger这个 大数据类型:
1.赋值:
BigInteger a=new BigInteger("1");
BigInteger b=BigInteger.valueOf(1);
2.运算:
① add(); 大整数相加
BigInteger a=new BigInteger(“23”);
BigInteger b=new BigInteger(“34”);
a. add(b);
②subtract(); 相减
③multiply(); 相乘
④divide(); 相除取整
⑤remainder(); 取余
⑥pow(); a.pow(b)=a^b
⑦gcd(); 最大公约数
⑧abs(); 绝对值
⑨negate(); 取反数
⑩mod(); a.mod(b)=a%b=a.remainder(b);
3.BigInteger构造函数:
一般用到以下两种:
BigInteger(String val);
将指定字符串转换为十进制表示形式;
BigInteger(String val,int radix);
将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger
4.基本常量:
A=BigInteger.ONE 1
B=BigInteger.TEN 10
C=BigInteger.ZERO 0
5.n.compareTo(BigInteger.ZERO)==0 // 相对于n=0
6.if(a[i].compareTo(n)>=0 &&a[i].compareTo(m)<=0) // a[i]>=n && a[i]<=m
了解完Biginteger的用法我们先测试一下
- Biginteger的基本运算
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger a = scanner.nextBigInteger();
BigInteger b = scanner.nextBigInteger();
System.out.println(a+"+"+b+"="+a.add(b)); // 相加
System.out.println(a+"-"+b+"="+a.subtract(b)); // 相减
System.out.println(a+"*"+b+"="+a.multiply(b)); // 相乘
System.out.println(a+"/"+b+"="+a.divide(b)); // 求商
System.out.println(a+"%"+b+"="+a.remainder(b)); // 求余
}
结果:
熟悉完Biginteger的用法后我们回到正题求斐波那契数列的第100个数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger a[] = new BigInteger[1000000];
a[0] = BigInteger.valueOf(1);
a[1] = BigInteger.valueOf(1);
int n = scanner.nextInt();
for (int i = 2; i < n; i++) {
a[i] =a[i-1].add(a[i-2]);
}
System.out.println(a[n-1]);
}
运行结果:
Biginteger不会有范围的限制,但是运行速度会比较慢一些,当我们要计算相对比较大的数时在使用比较合适。