0

I have a problem and I have to write a program (in JavaScript) to return the n-th Fibonacci number, this program works just fine when my input is not really big:

function nthFibConstantTime(n) {
    let phi = (1 + Math.sqrt(5)) / 2;
    return Math.round(Math.pow(phi, n) / Math.sqrt(5));
}
nthFibConstantTime(5) // 5
nthFibConstantTime(9) // 34
nthFibConstantTime(788) // 2.1516692574825388e+164

But, with input n, such as n = 1500, the program return Infinity and it's not what I expected.

function nthFibConstantTime(n) {
    let phi = (1 + Math.sqrt(5)) / 2;
    return Math.round(Math.pow(phi, n) / Math.sqrt(5));
}
nthFibConstantTime(1500) // Infinity

Can any body help me to write this program in JavaScript to return the n-th Fiboacci number, in case the output is too large which cannot represent by number in JavaScript, output should return this result with MOD 10^6+7 (n-th % 10^6 + 7).

Constraint input: An integer n (0 < n ≤ 10^15)

Nam V. Do
  • 630
  • 6
  • 27
  • Just use [BigInts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) instead. Maybe… – Sebastian Simon Oct 10 '19 at 13:42
  • @SebastianSimon it's going to be tricky to represent the square root of 5 as an integer. – Pointy Oct 10 '19 at 13:43
  • Let me/us know if this q/a answers you question. If so, I will mark your question a duplicate okay? https://stackoverflow.com/questions/16742578/bigdecimal-in-javascript – ControlAltDel Oct 10 '19 at 13:45
  • 2
    Fib[1500]=13551125668563101951636936867148408377786010712418497242133543153221487310873528750612259354035717265300373778814347320257699257082356550045349914102924249595997483982228699287527241931811325095099642447621242200209254439920196960465321438498305345893378932585393381539093549479296194800838145996187122583354898000 so I will recomend to work with strings, and make each term as one adition like we make with paper(very wide) and pencil ... – Anxon Pués Oct 10 '19 at 13:53

0 Answers0