アルゴリズムケース(1)------フィボナッチ数列
2104 ワード
一、紹介
フィボナッチ数列:開始する2つの値を与え、後の値は前の2つの値の重ね合わせであり、n番目の数の値を求める.
例えば:1,1,2,3,5,8,13,21......
二、実現方式
2.1配列遍歴方式
public class Fbnq {
/**
* n
* @param first
* @param second
* @param n n
* @return n
*/
public static int getFbnqNumber(int first, int second, int n) {
int[] arr = new int[1000];
arr[0] = first;
arr[1] = second;
if (n < 2) {
return arr[n];
}
for (int i = 2; i < n; i++) {
arr[i] = arr[i - 2] + arr[i - 1];
}
return arr[n - 1];
}
public static void main(String[] args) {
System.out.println(getFbnqNumber(1, 1, 12));
}
}
2.2三つの変数方式
public class Fbnq {
/**
* n
*
* @param first
* @param second
* @param n n
* @return n
*/
public static int getFbnqNumber(int first, int second, int n) {
if (n == 1) {
return first;
} else if (n == 2) {
return second;
}
int a = first, b = second, c = 0;
for (int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
public static void main(String[] args) {
System.out.println(getFbnqNumber(1, 1, 12));
}
}
2.3再帰方式
public class Fbnq {
/**
* n
*
* @param first
* @param second
* @param n n
* @return n
*/
public static int getFbnqNumber(int first, int second, int n) {
if (n == 1) {
return first;
} else if (n == 2) {
return second;
}
return getFbnqNumber(first, second, n - 2) + getFbnqNumber(first, second, n - 1);
}
public static void main(String[] args) {
System.out.println(getFbnqNumber(1, 1, 12));
}
}
2.1配列遍歴方式
public class Fbnq {
/**
* n
* @param first
* @param second
* @param n n
* @return n
*/
public static int getFbnqNumber(int first, int second, int n) {
int[] arr = new int[1000];
arr[0] = first;
arr[1] = second;
if (n < 2) {
return arr[n];
}
for (int i = 2; i < n; i++) {
arr[i] = arr[i - 2] + arr[i - 1];
}
return arr[n - 1];
}
public static void main(String[] args) {
System.out.println(getFbnqNumber(1, 1, 12));
}
}
2.2三つの変数方式
public class Fbnq {
/**
* n
*
* @param first
* @param second
* @param n n
* @return n
*/
public static int getFbnqNumber(int first, int second, int n) {
if (n == 1) {
return first;
} else if (n == 2) {
return second;
}
int a = first, b = second, c = 0;
for (int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
public static void main(String[] args) {
System.out.println(getFbnqNumber(1, 1, 12));
}
}
2.3再帰方式
public class Fbnq {
/**
* n
*
* @param first
* @param second
* @param n n
* @return n
*/
public static int getFbnqNumber(int first, int second, int n) {
if (n == 1) {
return first;
} else if (n == 2) {
return second;
}
return getFbnqNumber(first, second, n - 2) + getFbnqNumber(first, second, n - 1);
}
public static void main(String[] args) {
System.out.println(getFbnqNumber(1, 1, 12));
}
}