We say that two integers p and q are twins, if they are both primes and if q=p+2 (or p=q+2). F

or example, 5 and 7 are twins.

Write a twin function that determines whether two integers are twins.


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#include <math.h>

int twins(int p, int q) 
{
	int d,aux;
	if (p<0 ||q<0 || (p%2==0) || (q%2==0)||!(q==p+2 || p==q+2)) 
		return 0;
  	else 
	{ 
		// p and q are positive, odd, and verify p=q+2 or q=p+2
    		if (p>q)
		{ //exchange  p and q 
      			aux=p;
      			p=q;
      			q=aux;
    		}// here p<q
   		d=3;
    		while (d<sqrt(p) && (p%d!=0) && (q%d!=0)) 
			d=d+2; // find a divisor
    		if (d>sqrt(p)) // p and q are primes
     			return 1;
    		else 
			return 0;
  	}
}

void main()  
{
  	int a,b;
  	printf("Enter 2 integers: ");
  	scanf("%d%d",&a,&b);

  	if (twins(a,b)) 
		printf("%d and %d are twins\n",a,b);
  	else 
		printf("%d and %d are not twins\n",a,b);
	getch();
}

 

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Statically implemented Binary Tree