Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method for getting the continued fraction of an object. #52

Open
LarryBattle opened this issue Aug 12, 2013 · 0 comments
Open

Add method for getting the continued fraction of an object. #52

LarryBattle opened this issue Aug 12, 2013 · 0 comments

Comments

@LarryBattle
Copy link
Owner

Source:

/*
* Converse a fraction to a continued fraction
* @param {Number} a - numerator
* @param {Number} b - denominator
* @param {Number} limit - max number of elements returned.
* @return {Array} array of numbers
*/
var fractionToContinuedFraction = function (a, b, limit) {
    limit = limit || 1e3;
    var arr = [];
    a = +a;
    b = +b;
    while (0 < limit-- && a && b && (a !== 1 || a / b !== 1)) {
        arr.push( Math.floor( a/b ) );
        a %= b;
        tmp = b;
        b = a;
        a = tmp;
    }
    return arr;
}

Bug:

  • Add condition for 0 and Infinity.

Does the opposite.

var continuedFractionToFraction = function (arr) {
    if(typeof arr !== "object"){
        return null;
    }
    var a = 1,
    b = 1,
    tmp,
    i = arr.length;
    while(i--){
        a += b * arr[i];
        tmp = b;
        b = a;
        a = tmp;
    }
    return [a, b];
};

Need to add unit tests. There a bug in the code but will check it out later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant