Skip to content

Add Twin Primes algorithm #1024

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Maths/TwinPrime.js
Original file line number Diff line number Diff line change
@@ -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 changes: 10 additions & 0 deletions Maths/test/TwinPrime.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
})