prabaprakash / Hackerrank-JavaScript-Solutions

Solved entire Easy, few Medium Problems. A total of 171/563 challenges solved by JavaScript
https://www.hackerrank.com/prabaprakash
123 stars 64 forks source link

Fibonacci Modified #4

Closed prabaprakash closed 4 years ago

prabaprakash commented 4 years ago
big add
const add = (a, b) => {
    let carry = 0;
    let i = 0;
    for (i = 0; i < b.length; i++) {
        let n = a[i] + b[i] + carry;
        a[i] = n % 10;
        carry = Math.floor(n / 10);
    }
    while (carry > 0) {
        a[i] = typeof a[i] !== 'undefined' ? a[i] : 0
        let n = a[i] + carry;
        a[i] = n % 10;
        carry = Math.floor(n / 10);
        i++;
    }
    return a;
}
// big mul
const mul = (b, a) => {
    let out = [];
    let k = 0, carry = 0;
    for (let i = 0; i < a.length; i++) {
        for (let j = 0; j < b.length; j++) {
            let e = typeof out[k] !== 'undefined' ? out[k] : 0;
            let n = (a[i] * b[j]) + carry + e;
            out[k] = n % 10;
            carry = Math.floor(n / 10);
            k++;
        }
        if (carry > 0) {
            out[k] = carry;
            carry = 0;
        }
        k = i + 1;
    }
    return out;
}
prabaprakash commented 4 years ago

the above multiply functions operation needs optimization

prabaprakash commented 4 years ago

solved by predefined bigint in js

function fibonacciModified(t1, t2, n) {
    let hash = {};
    hash[1] = BigInt(t1);
    hash[2] = BigInt(t2);
    for (let i = 3; i < n + 1; i++) {
        hash[i] = (hash[i - 1] * hash[i - 1]) + hash[i - 2];
    }
    return hash[n]
}