Skip to content

Commit 69a397c

Browse files
authored
merge: Added LucasSeries Implementation (TheAlgorithms#808)
* Added LucasSeries * Added more tests and renamed function * Changed RangeError to TypeError
1 parent e8d862c commit 69a397c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

Maths/LucasSeries.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Program to get the Nth Lucas Number
3+
Article on Lucas Number: https://en.wikipedia.org/wiki/Lucas_number
4+
Examples:
5+
> loopLucas(1)
6+
1
7+
> loopLucas(20)
8+
15127
9+
> loopLucas(100)
10+
792070839848372100000
11+
*/
12+
13+
/**
14+
* @param {Number} index The position of the number you want to get from the Lucas Series
15+
*/
16+
function lucas (index) {
17+
// index can't be negative
18+
if (index < 0) throw new TypeError('Index cannot be Negative')
19+
20+
// index can't be a decimal
21+
if (Math.floor(index) !== index) throw new TypeError('Index cannot be a Decimal')
22+
23+
let a = 2
24+
let b = 1
25+
for (let i = 0; i < index; i++) {
26+
const temp = a + b
27+
a = b
28+
b = temp
29+
}
30+
return a
31+
}
32+
33+
export { lucas }

Maths/test/LucasSeries.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { lucas } from '../LucasSeries'
2+
3+
describe('Nth Lucas Number', () => {
4+
it('should return the 20th Lucas Number', () => {
5+
expect(lucas(20)).toBe(15127)
6+
})
7+
8+
it('should return the 20th Lucas Number', () => {
9+
expect(lucas(0)).toBe(2)
10+
})
11+
12+
it('should return the 20th Lucas Number', () => {
13+
expect(lucas(100)).toBe(792070839848372100000)
14+
})
15+
})

0 commit comments

Comments
 (0)