Professional Documents
Culture Documents
Fibonacci
Fibonacci
( רקורסיבי ואינדוקטיבי (ע"י לולאה:( בשני אופניםO(log n חישוב מספרי פיבונאצי בסיבוכיות של
public class Fibonacci {
פונקצית מעטפת//
public static int fibbRecursion(int n){
int [][] mat={{1,1}, {1,0}};
int[][] ans = fibbRecursion(mat, n);
return ans[0][0];
}
חישוב רקורסיבי//
public static int[][] fibbRecursion(int mat[][], int n){
int [][] mat1={{1,0}, {0,1}};
if ( n == 0){
return mat1;
}
else if (n%2 == 0){
return fibbRecursion(MyLibrary.matrixSqMulti(mat,mat),n/2);
}
else{
return
MyLibrary.matrixSqMulti(mat,fibbRecursion(MyLibrary.matrixSqMulti(mat,mat),(n -
1)/2));
}
}
חישוב אינדוקטיבי//
public static int fibb(int n){
int matN[][] = {{1,1},{1,0}};
int result[][] = new int[2][2];
if (n%2 != 0 ){
result[0][0]=1; result[0][1]=1; result[1][0]=1;
result[1][1]=0;
}
else{
שימוש במטריצה יחידה//
result[0][0]=1; result[0][1]=0; result[1][0]=0;
result[1][1]=1;
}
n = n/2;
while (n != 0){
matN = MyLibrary.matrixSqMulti(matN, matN);
if ( (n % 2) != 0 ){
result = MyLibrary.matrixSqMulti(result, matN);
}
n = n/2;
} // end while
return result[0][0];
}
תוכנית בדיקה//
public static void main(String[] args) {
for(int i=1; i<=10; i++){
System.out.print("fibb("+i+")="+fibbRecursion(i)+", ");
}
System.out.println();
for(int i=1; i<=10; i++){
System.out.print("fibb("+i+")="+fibb(i)+", ");
}
System.out.println();{{