Last active
March 3, 2020 09:57
-
-
Save ntankovic/5248612e8f289c77f055b748c75866bc to your computer and use it in GitHub Desktop.
Fibonacci - fast&slow
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
import express from 'express'; | |
const app = express() | |
app.get('/fibonacci/:n', (req, res) => { | |
let fibonacci_slow = (n) => { | |
if (n == 0) { | |
return 0 | |
} | |
else if (n <= 2) { | |
return 1 | |
} | |
return fibonacci_slow(n-1) + fibonacci_slow(n-2) | |
} | |
let fibonacci_fast = n => { | |
if (n == 0) { | |
return 0; | |
} else if (n <= 2) { | |
return 1; | |
} | |
let n1 = 1; | |
let n2 = 0; | |
let ni; | |
for (let i = 2; i <= n; i++) { | |
ni = n1 + n2; | |
n2 = n1; | |
n1 = ni; | |
} | |
return ni; | |
}; | |
let n = req.params.n | |
res.json({ | |
answer: fibonacci_fast(Number(n)) | |
}) | |
}) | |
app.listen(port, () => console.log(`Listening on http://localhost:${port}!`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment