Skip to content

Commit 92a81a2

Browse files
authored
merge: Add Twin Primes algorithm (TheAlgorithms#1024)
* Create TwinPrime.js * Update TwinPrime.js * Create TwinPrime.test.js * Update TwinPrime.js * Update TwinPrime.js * Add suggestions * Update TwinPrime.test.js * Update TwinPrime.js * Styling
1 parent 0357a23 commit 92a81a2

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

Maths/TwinPrime.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { PrimeCheck } from './PrimeCheck'
2+
3+
/**
4+
* @function twinPrime
5+
* Gets the 'twin prime' of a prime number.
6+
*
7+
* @param {Integer} n The number to find the twin prime of.
8+
* @returns {Integer} Either the twin, or -1 if n or n + 2 is not prime.
9+
*
10+
* @see https://en.wikipedia.org/wiki/Twin_prime
11+
*
12+
* @example twinPrime(5) = 7
13+
* @example twinPrime(4) = -1
14+
*/
15+
function twinPrime (n) {
16+
const prime = PrimeCheck(n)
17+
18+
if (!prime) {
19+
return -1
20+
}
21+
22+
if (!PrimeCheck(n + 2)) {
23+
return -1
24+
}
25+
26+
return n + 2
27+
}
28+
29+
export { twinPrime }

Maths/test/TwinPrime.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { twinPrime } from '../TwinPrime.js'
2+
3+
describe('Twin Primes', () => {
4+
it('Should be valid twin primes', () => {
5+
expect(twinPrime(3)).toBe(5)
6+
expect(twinPrime(5)).toBe(7)
7+
expect(twinPrime(4)).toBe(-1)
8+
expect(twinPrime(17)).toBe(19)
9+
})
10+
})

0 commit comments

Comments
 (0)