• Write the function « int Prime(int a) » that verifies if an integer « a » is a prime number or not.
  • Write the function « int NextPrime (int a) » that returns the smallest prime number greater than « a ».
    Example: NextPrime(9) should return 11.
    NextPrime(11) should return 13.
  • Two consecutive odd numbers that are both prime numbers are called « twin prime numbers ». Using the two functions of parts 1 and 2, write a C program that prints all the twin prime numbers that are < 1000. For example, the first 5 lines of the program output should be :
    3 5
    5 7
    11 13
    17 19
    29 31 

Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <math.h>
int Prime(int nb)
{
	int i;
	for (i = 2; i <= sqrt(nb); i++)
		if (nb%i == 0)
			return 0;
	return 1;
}

int NextPrime(int nb)
{
    while(!Prime(nb))
        nb++;
    return nb;
}

int main()
{
    int i, j;
    
    for(i=1; i <100;i++)
        if(i%2 && Prime(i) && NextPrime(i+1)==i+2 && Prime(i+2))
            printf("%d %d\n",i,i+2);
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using quick-sort algorithm