Subscribe Us

Twin Prime Numbers In C++

Twin Prime Numbers


C++ Program To Check Twin Prime Numbers Or Not

A twin prime is a prime number that is Either 2 less or 2 more than another prime number
A twin prime is a prime that has a prime gap of Two

Example:
Given Numbers : 11 and 13
11 and 13 are Twin Prime Number Because
11 and 13 Both are Prime Numbers and Gap Between Them are 2 .
Example:
Given Numbers : 11 and 19
11 and 19 are Not Twin Prime Number Because
11 and 19 Both are Prime Numbers But Gap Between Them are Not 2 .

Source Code

//C++ Program To Check Twin Prime Number
#include<iostream.h>
#include<conio.h>
 void main()
   {
     int num1,num2;
     int i,count1=0,count2=0;
     cout<<"Enter First Number : ";
     cin>>num1;
     cout<<"Enter Second Number : ";
     cin>>num2;
     // Count The Factors of num1
     for( i=1;i<=num1;i++ )
       {
         if(num1%i==0)
           count1++;
       }
     // Count The Factors of num2
     for( i=1;i<=num2;i++ )
       {
         if(num2%i==0)
           count2++;
       }
     if( (count1==2 && count2==2)&& ((num1-num2)==2 || (num1-num2)==-2 ))
        cout<<num1<<" and "<<num2<<" are Twin Prime Numbers ";
     else
       cout<<num1<<" and "<<num2<<" are Not Twin Prime Numbers ";
     getch();
   }

Output

Sample Input :
Enter First Number : 11
Enter Second Number : 13
Sample Output:
11 and 13 are Twin Prime Numbers

Sample Input :
Enter First Number : 17
Enter Second Number : 23
Sample Output:
17 and 23 are Not Twin Prime Numbers