mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 17:50:39 +08:00
merge: Add Twin Primes algorithm (#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
This commit is contained in:
29
Maths/TwinPrime.js
Normal file
29
Maths/TwinPrime.js
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import { PrimeCheck } from './PrimeCheck'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @function twinPrime
|
||||||
|
* Gets the 'twin prime' of a prime number.
|
||||||
|
*
|
||||||
|
* @param {Integer} n The number to find the twin prime of.
|
||||||
|
* @returns {Integer} Either the twin, or -1 if n or n + 2 is not prime.
|
||||||
|
*
|
||||||
|
* @see https://en.wikipedia.org/wiki/Twin_prime
|
||||||
|
*
|
||||||
|
* @example twinPrime(5) = 7
|
||||||
|
* @example twinPrime(4) = -1
|
||||||
|
*/
|
||||||
|
function twinPrime (n) {
|
||||||
|
const prime = PrimeCheck(n)
|
||||||
|
|
||||||
|
if (!prime) {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!PrimeCheck(n + 2)) {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
return n + 2
|
||||||
|
}
|
||||||
|
|
||||||
|
export { twinPrime }
|
10
Maths/test/TwinPrime.test.js
Normal file
10
Maths/test/TwinPrime.test.js
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { twinPrime } from '../TwinPrime.js'
|
||||||
|
|
||||||
|
describe('Twin Primes', () => {
|
||||||
|
it('Should be valid twin primes', () => {
|
||||||
|
expect(twinPrime(3)).toBe(5)
|
||||||
|
expect(twinPrime(5)).toBe(7)
|
||||||
|
expect(twinPrime(4)).toBe(-1)
|
||||||
|
expect(twinPrime(17)).toBe(19)
|
||||||
|
})
|
||||||
|
})
|
Reference in New Issue
Block a user