[5359 views]
A number is said to be a prime number when it has only two factors, that is, when the factors of the number are 1 and the number itself.
Example: 2, 3, 11, 17, etc.
Two numbers are said to be twin prime numbers when both the numbers are prime and there is exactly one composite number present between them. In other words, when the difference between two prime numbers is 2, they are known as twin prime numbers. Twin prime numbers are also known as prime twin or prime pair numbers.
For example: 3 and 5.
5 – 3 = 2, therefore 3 and 5 are twin prime numbers.
Other examples include: 5 and 7, 11 and 13, 17 and 19, 41 and 43, etc.
Now let’s take a look at the algorithm and flowchart to check whether two given numbers are twin prime or not, for better understanding.
We will start off by taking both the numbers to be checked as user input and store them in variables ‘n1’ and ‘n2’. In this problem, we must find out the number of factors of each number, to determine whether they are prime or not. To do so, we will first initialize the number of factors, ‘f1’ and ‘f2’ respectively, as 0. To find the number of factors of the first number, we will start a loop from 1 to n1, where the loop variable is ‘i’. If n1%i=0, f1 is incremented by 1. In this line we are simply checking whether the number n1 is divisible by ‘i’ or not. If yes, the number of factors of n1, that is, f1 is incremented.
In the same way, we will run another loop from 1 to n2, to calculate the number of factors of n2. After that, we calculate the difference between the two numbers.
That being done, we will now check whether the difference, f1 and f2 are equal to 2 or not. If yes, the numbers are twin prime, else, they are not twin prime. Remember, if a number is prime, it will have exactly 2 factors and the difference between twin prime numbers is 2.
Note: Here ‘%’ is the modulus operator which returns the remainder value after division.
If we take two numbers, 5 and 7:
Factors of 5: 1,5
Factors of 7: 1,7
So, for both the numbers, f1 and f2 will be equal to 2.
The difference will be: 7-5=2
Therefore, difference, f1 and f2 are 2. Hence, 5 and 7 are twin prime numbers.