Created
August 2, 2013 17:33
-
-
Save tomca32/6141736 to your computer and use it in GitHub Desktop.
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
; | |
//Project Euler Problem #230 - Fibonacci Words | |
(function (exports) { | |
// var BigNumber = require('bignumber.js'); | |
var SQ5 = Math.sqrt(5); | |
var RECSQ5 = 1/SQ5; | |
var C1 = (1+SQ5)/2; | |
var C2 = (1-SQ5)/2; | |
var PHI = C1; | |
function getNumber (n) { | |
// console.log((127+19*n)*(Math.pow(7,n))); | |
return (127+19*n)*(Math.pow(7,n)); | |
} | |
exports.nFibo = function (n) { | |
//Returns the nth element of Fibonacci Sequence | |
return Math.round(RECSQ5 * (Math.pow(C1,n) - Math.pow(C2,n))); | |
}; | |
exports.nthDigit = function (n) { | |
// console.log(n); | |
if (n < 1) return undefined; | |
return (Math.floor(n*PHI) - Math.floor((n-1)*PHI)-1) === 0 ? "A" : "B"; | |
}; | |
exports.nWords = function(word, n) { | |
//Returns the number of sequence that contains nth number and its length | |
var l = word.length, result, prev = 0; | |
// n = getNumber(n); | |
// console.log(l, n); | |
// if (n===1) return {nSequence:1, s} | |
for (var i = 1; i < n; i += 1) { | |
result = exports.nFibo(i); | |
// console.log(n, i, result); | |
if ((result * l) >= n) return { | |
nSequence: i, | |
sLength: result, | |
prevLength: prev | |
}; | |
prev += result; | |
} | |
}; | |
function D (a,b,n) { | |
var words = nWords(a,n), nu = (n%a.length)-1, res; | |
if (nu <0) nu = a.length-1; | |
// console.log("Words", words, nu); | |
var letter = nthDigit(Math.ceil(n/a.length)+words.prevLength); | |
if (letter === "A") { | |
res = a; | |
} else { | |
res = b; | |
} | |
// console.log(res.substr(nu,1)); | |
return res.substr(nu,1); | |
} | |
exports.smash = function (a,b,n) { | |
// console.log(D(a, b, getNumber(n))); | |
// return (D(a,b,n)); | |
var result = D(a,b,getNumber(n)); | |
console.log(typeof result, n); | |
if (n===0) return result; | |
return result + (smash(a,b,n-1)); | |
}; | |
}(typeof window === 'undefined' ? global : window)); | |
var A = "1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; | |
var B = "8214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196"; | |
var testA = "1415926535", testB = "8979323846"; | |
// console.log(smash(A,B,9)); | |
console.log(smash(A,B, 17)); | |
// console.log(nthDigit(1)); | |
// console.log(nWords(testA, 52)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment