计算菲波那切数列 前50项
public class Main {
public static void main(String[] args) {
// temp 1 表示第一个数 temp 2 表示第二个数
// 用tmp 作为中转站使 temp1 和 temp2在进行循环时可以向后移动(不使用数组减少空间复杂度)
long temp1 = 1;
long temp2 = 1;
long tmp = 0;
System.out.println(1 + ":" + temp1 + " ");
System.out.println(2 + ":" + temp2 + " ");
for (int i = 2; i < 50; i++) {
/*
使用 tmp 作为中转站,使temp1 和 temp2向后移动
*/
// tmp 记录temp1 的值
tmp = temp1;
// 之后将temp1移动到temp2的位置
temp1 = temp2;
// temp2则赋值为原temp1 和 temp2 之和,
// 即移动到temp2后一个位置,之后循环移动即可。
temp2 = temp2 +tmp;
System.out.println(i + 1 + ":" + temp2 + " ");
}
}
}