Skip to content

Commit e1be882

Browse files
algorithm: Twin prime (TheAlgorithms#7980)
* feat: Add twin prime algorithm * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix: Fix broken import statement Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 7b2eca0 commit e1be882

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

maths/twin_prime.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
== Twin Prime ==
3+
A number n+2 is said to be a Twin prime of number n if
4+
both n and n+2 are prime.
5+
6+
Examples of Twin pairs: (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), ...
7+
https://en.wikipedia.org/wiki/Twin_prime
8+
"""
9+
10+
# Author : Akshay Dubey (https://github.com/itsAkshayDubey)
11+
from maths.prime_check import is_prime
12+
13+
14+
def twin_prime(number: int) -> int:
15+
"""
16+
# doctest: +NORMALIZE_WHITESPACE
17+
This functions takes an integer number as input.
18+
returns n+2 if n and n+2 are prime numbers and -1 otherwise.
19+
>>> twin_prime(3)
20+
5
21+
>>> twin_prime(4)
22+
-1
23+
>>> twin_prime(5)
24+
7
25+
>>> twin_prime(17)
26+
19
27+
>>> twin_prime(0)
28+
-1
29+
>>> twin_prime(6.0)
30+
Traceback (most recent call last):
31+
...
32+
TypeError: Input value of [number=6.0] must be an integer
33+
"""
34+
if not isinstance(number, int):
35+
raise TypeError(f"Input value of [number={number}] must be an integer")
36+
if is_prime(number) and is_prime(number + 2):
37+
return number + 2
38+
else:
39+
return -1
40+
41+
42+
if __name__ == "__main__":
43+
import doctest
44+
45+
doctest.testmod()

0 commit comments

Comments
 (0)