最近无意接触到 斐波那契数列。百科了一下~~~
斐波纳契数列(Fibonacci Sequence),又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、……在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)在现代物理、准晶体结构、化学等领域,斐波纳契数列都有直接的应用。
Java版
//main方法
public static void main(String[] args)
{
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(1);
result.add(1);
addNewValue(result);
System.out.println(result);
System.out.println(addNum(5));
System.out.println(fibonacci(5));
}
//1
public static void addNewValue(ArrayList<Integer> array)
{
if (array.size() <= 5)
{
array.add(array.get(array.size() - 1) + array.get(array.size() - 2));
addNewValue(array);
}
}
// 2
public static long addNum(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return addNum(num - 1) + addNum(num - 2);
}
}
//3
public static BigInteger fibonacci(int num)
{
if (num == 0)
{
return new BigInteger("0");
}
else if (num == 1)
{
return new BigInteger("1");
}
else
{
BigInteger b0 = BigInteger.ZERO;
BigInteger b1 = BigInteger.ONE;
BigInteger fn = BigInteger.ZERO;
for (int i = 1; i <= num; i++)
{
fn = b0.add(b1);
b0 = b1;
b1 = fn;
}
return fn;
}
}
Shell版
#1
#!/bin/bash
echo "Fibonacci script"
echo "Press a number here..."
read number
if [ $number -le 0 ]
then
echo "You have something wrong.The number must be great then 0."
exit 1
fi
for((i=0;i<$number;i++))
do
if(($i-2>=0))
then
((array[$i]=${array[$i-1]}+${array[$i-2]}))
else
((array[$i]=$i))
fi
echo array[$i]=${array[$i]}
done
sum=0
for((j=0;j<10;j++))
do
sum=$(($sum+${array[$j]}))
done
echo "$sum"
#2
#!/bin/bash
#Fibonacci Sequence
echo "Press a number here..."
read number
if [ $number -le 0 ]
then
echo "You have something wrong.The number must be great then 0."
exit 1
fi
echo "Well, you wanna print between 1 and $number, and count them."
fibonacci(){
arg1=0
arg2=1
for((i=1;i<=$number;i++))
do
((arg3=$arg1+$arg2))
echo "Seq: $arg1+$arg2=$(($arg1+$arg2))"
sum=$(($sum+$arg3))
arg1=$arg2
arg2=$arg3
done
echo "$sum"
}
fibonacci