mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 07:29:47 +08:00
merge: Added LucasSeries Implementation (#808)
* Added LucasSeries * Added more tests and renamed function * Changed RangeError to TypeError
This commit is contained in:
33
Maths/LucasSeries.js
Normal file
33
Maths/LucasSeries.js
Normal file
@ -0,0 +1,33 @@
|
||||
/*
|
||||
Program to get the Nth Lucas Number
|
||||
Article on Lucas Number: https://en.wikipedia.org/wiki/Lucas_number
|
||||
Examples:
|
||||
> loopLucas(1)
|
||||
1
|
||||
> loopLucas(20)
|
||||
15127
|
||||
> loopLucas(100)
|
||||
792070839848372100000
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {Number} index The position of the number you want to get from the Lucas Series
|
||||
*/
|
||||
function lucas (index) {
|
||||
// index can't be negative
|
||||
if (index < 0) throw new TypeError('Index cannot be Negative')
|
||||
|
||||
// index can't be a decimal
|
||||
if (Math.floor(index) !== index) throw new TypeError('Index cannot be a Decimal')
|
||||
|
||||
let a = 2
|
||||
let b = 1
|
||||
for (let i = 0; i < index; i++) {
|
||||
const temp = a + b
|
||||
a = b
|
||||
b = temp
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
export { lucas }
|
15
Maths/test/LucasSeries.test.js
Normal file
15
Maths/test/LucasSeries.test.js
Normal file
@ -0,0 +1,15 @@
|
||||
import { lucas } from '../LucasSeries'
|
||||
|
||||
describe('Nth Lucas Number', () => {
|
||||
it('should return the 20th Lucas Number', () => {
|
||||
expect(lucas(20)).toBe(15127)
|
||||
})
|
||||
|
||||
it('should return the 20th Lucas Number', () => {
|
||||
expect(lucas(0)).toBe(2)
|
||||
})
|
||||
|
||||
it('should return the 20th Lucas Number', () => {
|
||||
expect(lucas(100)).toBe(792070839848372100000)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user