Created
March 23, 2014 03:15
-
-
Save Nkzn/9718108 to your computer and use it in GitHub Desktop.
フィボナッチ数列の第N項を算出するコードを2パターンで書いてみたよ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
* { | |
margin: 0; | |
padding: 0; | |
border: 0; | |
} | |
body { | |
background: #dfd; | |
font: 30px sans-serif; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h3>ループ版</h3> | |
<p id='fibonacci_result1'></p> | |
<h3>漸化式の一般項版</h3> | |
<p id='fibonacci_result2'></p> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 算出する項の数を定義 | |
var N = 50; | |
/* | |
ループを使うバージョン | |
*/ | |
function fibonacci1(n) { | |
// フィボナッチ数列を算出 | |
var fibo_ary = []; // 配列を初期化する | |
fibo_ary[0] = 0; | |
fibo_ary[1] = 1; | |
for (var n=2; n <= N; n++) { | |
fibo_ary[n] = fibo_ary[n-1] + fibo_ary[n-2]; | |
} | |
// 配列の中身をコンソールに出してみる(おまけ) | |
console.log('array -> ' + fibo_ary.join(",")); | |
return fibo_ary[N] | |
} | |
// 第N項を表示 | |
document.getElementById('fibonacci_result1').innerHTML = fibonacci1(N); | |
/* | |
漸化式の一般項を使うバージョン | |
参考:http://keisan.casio.jp/exec/system/1161228773 | |
*/ | |
function fibonacci2(n) { | |
// 分母 | |
var denominator = Math.pow(2, n) * Math.sqrt(5); | |
// 分子 | |
var numerator = Math.pow(1 + Math.sqrt(5), n) - Math.pow(1 - Math.sqrt(5), n); | |
return numerator / denominator; | |
} | |
// 第N項を表示 | |
document.getElementById('fibonacci_result2').innerHTML = fibonacci2(N); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment