Fibonacci Number
Formula to get the results of Fibonacci terms
HTML
<!-- stitch this with the module declare in Javascript -->
<body ng-app="myApp">
<div ng-controller="MainCtrl">
<table>
<tr>
<td>For term (0)</td>
</tr>
<tr>
<td><b>The value is {{value0}}</b><br/><br/></td>
</tr>
<tr>
<td>For term (1)</b>
</td>
</tr>
<tr>
<td><b>The value is {{value1}}</b><br/><br/></td>
</tr>
<tr>
<td>For term (8181)</b>
</td>
</tr>
<tr>
<td><b>The value is {{value8181}}</b><br/><br/></td>
</tr>
</table>
</div>
</body>
JavaScript
// declare a module
var myApp = this.angular.module('myApp', []);
// declare a controller
myApp.controller('MainCtrl', function($scope) {
$scope.array;
//Function to return the fibonacci number
//Some basic ideas
//1. Positive values below or equals to 1 will return the same value
//2. For positive values after 1, we will apply the formula
//func(n-1) + func(n-2)
//3. We are going to start from 0 ~ to the number so as we
//derive a value for a term, we will store it in an array and resuse it
//when needed
$scope.func = function(input) {
$scope.array = [];
$scope.calc = function(input) {
//Try to search for the value in the array
//if it exists, we will return it
if ($scope.findIndex(input) != undefined) {
result = $scope.findIndex(input);
} else {
//if that array doesn't have that term + value pair,
//we will apply this formula
var base = 0;
while (base <= input) {
var result = 0;
//if the value is lesser or equals 1
if (base <= 1) {
result = new BigNumber(base);
} else {
//else the formula func(n-1) + func(n-2)
result = new BigNumber($scope.calc(base - 1)).add($scope.calc(base - 2));
}
//We will push the term + value pair into the array for future purposes
if ($scope.findIndex(base) == undefined) {
$scope.array.push({
id: base,
val: result
});
}
base++;
}
}
return result;
}
return $scope.calc(input).toString();
}
//Function to check if an earlier term + value do exist
//and return the value of that term
$scope.findIndex = function(id) {
var result = undefined;
for (var i = 0; i < $scope.array.length; i++) {
if ($scope.array[i].id == id) {
return $scope.array[i].val;
}
}
return result;
}
$scope.value0 =...