What are C Twin Primes Program- Best C Language Course For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

C Twin Primes Program

Lecture 25 of our free C programming course: write a twin primes program in C, handle loop boundaries and cut function calls with the 6k pattern.

Welcome to the next lecture of our free C programming course. Here we write a twin primes program in C that prints every pair of primes below 500 that differ by exactly 2, such as 17 and 19. The program is short, but it teaches an important habit of embedded C programming: build bigger answers by calling a small, trusted function more than once.

This free C tutorial reuses the prime test from the previous lecture. We then go one step further and measure how many times the function is called, so you can see how a little mathematics makes a program more than two and a half times cheaper. That kind of reasoning is exactly what you need when a microcontroller has limited time and power.

What You Will Learn

  • What twin primes are and how to recognise them
  • How to write a twin primes program in C with a simple loop and a helper function
  • Why the loop must step over odd numbers only
  • How to test boundary conditions so that the last pair is neither missed nor invented
  • Why every twin prime pair above (3, 5) has the form 6k – 1 and 6k + 1
  • How to count function calls to compare two versions of the same program
  • Why 3, 5 and 7 are the only three primes in a row with gaps of 2

Prerequisites

Before you start

  • You completed the previous lecture and can use a function such as ep_is_prime().
  • You know the logical AND operator && and how short-circuit evaluation works.
  • You can read a for loop with a step of 2.

What Are Twin Primes?

Twin primes are two prime numbers that differ by exactly 2. In other words they are two consecutive odd numbers that are both prime. The pair 17 and 19 qualifies, because both numbers are prime and 19 – 17 = 2. The pair 23 and 25 does not, because 25 is divisible by 5. The pair 2 and 3 does not qualify either, because they differ by 1 and 2 is the only even prime.

A twin primes program in C therefore has to answer two prime questions for each candidate: is the number prime, and is the number plus 2 also prime? If both answers are yes, the pair is printed.

Examples of candidate pairs

Twin primes

(3, 5) (11, 13) (17, 19) (29, 31)

Not twin primes

(7, 9) because 9 = 3 x 3 (13, 15) because 15 = 3 x 5 (23, 25) because 25 = 5 x 5 (2, 3) because the gap is 1

Algorithm for the Twin Primes Program in C

  1. Start with the first odd number that can begin a pair, which is 3.
  2. Test whether p is prime and whether p + 2 is prime.
  3. If both tests pass, print the pair and increase a counter.
  4. Move to the next odd number with p += 2.
  5. Stop when p + 2 would reach 500, so that both members stay below the limit.
Flow of the twin primes loop
1

Start

Set p = 3 and pairs = 0.

2

Check limit

Continue while p + 2 < 500.

3

Two questions

Ask ep_is_prime(p) and ep_is_prime(p + 2) joined by &&.

4

Print and count

When both answers are 1, print the pair and add 1 to pairs.

5

Advance

Add 2 to p and repeat. Print the total at the end.

Notice the role of the && operator. C evaluates its left side first, and if that side is false the right side is skipped completely. When p is not prime, the second call to ep_is_prime(p + 2) never happens. That short-circuit behaviour already saves time without any extra code.

Complete Twin Primes Program in C

Program twin.c

#include <stdio.h>

static int ep_is_prime(unsigned n)
{
    if (n < 2) return 0;
    for (unsigned d = 2; d * d <= n; d++)
        if (n % d == 0) return 0;
    return 1;
}

int main(void)
{
    unsigned pairs = 0;

    for (unsigned p = 3; p + 2 < 500; p += 2) {
        if (ep_is_prime(p) && ep_is_prime(p + 2)) {
            printf("(%u, %u)\n", p, p + 2);
            pairs++;
        }
    }
    printf("pairs = %u\n", pairs);
    return 0;
}

Output:

(3, 5)
(5, 7)
(11, 13)
(17, 19)
(29, 31)
(41, 43)
(59, 61)
(71, 73)
(101, 103)
(107, 109)
(137, 139)
(149, 151)
(179, 181)
(191, 193)
(197, 199)
(227, 229)
(239, 241)
(269, 271)
(281, 283)
(311, 313)
(347, 349)
(419, 421)
(431, 433)
(461, 463)
pairs = 24
gcc -std=c11 -Wall -Wextra -o twin twin.c
./twin

There are 24 twin prime pairs below 500. The last one is (461, 463). The candidate (497, 499) is correctly rejected because 497 = 7 x 71. Pairs may overlap: the numbers 5 and 7 appear in two pairs, (3, 5) and (5, 7).

RangeTwin prime pairs found
Below 1008
100 to 1997
200 to 2994
300 to 3992
400 to 4993
Twin primes below 500
24
Pairs found
(461, 463)
Largest pair
8
Pairs below 100

Boundary Conditions: Where the Loop Must Stop

Loop limits are the place where beginners make off-by-one mistakes. The task says the pairs must be less than 500. The second number of a pair is p + 2, so the loop must stop before p + 2 reaches 500. We wrote the condition p + 2 < 500 to express exactly that.

Loop conditionEffectVerdict
p < 500Allows p = 499, so the pair (499, 501) is tested and 501 is outside the rangeToo generous
p + 2 < 500Both members of every printed pair are below 500Correct
p < 498Same effect here, but the meaning is hiddenWorks, but less clear

Writing p + 2 < 500 documents the intention in the code itself. A reader does not have to calculate anything.

Making the Twin Primes Program in C Faster

Our program calls ep_is_prime() a lot. To measure rather than guess, we added a global counter that increases on every call and compared two versions. The first is the plain scan above. The second uses a fact from number theory.

The 6k – 1 and 6k + 1 pattern

Every integer can be written as 6k, 6k + 1, 6k + 2, 6k + 3, 6k + 4 or 6k + 5. The forms 6k, 6k + 2 and 6k + 4 are even, and 6k + 3 is a multiple of 3. After 3, a prime must therefore be of the form 6k – 1 or 6k + 1. For a twin pair of two numbers that differ by 2, the only form that fits is 6k - 1 and 6k + 1. So after handling (3, 5) by hand, we can examine only one candidate for every six numbers.

Why only 6k – 1 and 6k + 1 can work

6k, 6k + 2, 6k + 4

Even numbers, divisible by 2, so never prime above 2.

6k + 3

A multiple of 3, so never prime above 3.

6k – 1 and 6k + 1

The only remaining forms. Two of them two apart make a twin pair candidate.

Program twin6.c (measured)

#include <stdio.h>

static unsigned long calls = 0;

static int ep_is_prime(unsigned n)
{
    calls++;
    if (n < 2) return 0;
    for (unsigned d = 2; d * d <= n; d++)
        if (n % d == 0) return 0;
    return 1;
}

int main(void)
{
    unsigned pairs = 0;

    /* plain scan over odd candidates */
    for (unsigned p = 3; p + 2 < 500; p += 2)
        if (ep_is_prime(p) && ep_is_prime(p + 2))
            pairs++;
    printf("plain: pairs=%u is_prime calls=%lu\n", pairs, calls);

    calls = 0;
    pairs = 0;
    /* (3,5) separately, then only 6k-1 and 6k+1 */
    if (ep_is_prime(3) && ep_is_prime(5)) { printf("(3, 5) "); pairs++; }
    for (unsigned k = 1; 6 * k + 1 < 500; k++) {
        unsigned lo = 6 * k - 1;
        if (ep_is_prime(lo) && ep_is_prime(lo + 2)) {
            printf("(%u, %u) ", lo, lo + 2);
            pairs++;
        }
    }
    printf("\n6k scan: pairs=%u is_prime calls=%lu\n", pairs, calls);
    return 0;
}

Output:

plain: pairs=24 is_prime calls=341
(3, 5) (5, 7) (11, 13) (17, 19) (29, 31) (41, 43) (59, 61) (71, 73) (101, 103) (107, 109) (137, 139) (149, 151) (179, 181) (191, 193) (197, 199) (227, 229) (239, 241) (269, 271) (281, 283) (311, 313) (347, 349) (419, 421) (431, 433) (461, 463)
6k scan: pairs=24 is_prime calls=133
VersionPairs foundCalls to ep_is_prime
Plain scan over odd numbers24341
6k – 1 and 6k + 1 scan24133

Both versions find the same 24 pairs, so the second is correct, and it needs 133 calls instead of 341, which is about 2.6 times fewer. Notice that the improvement came from thinking, not from clever C syntax. On a small microcontroller this is the kind of optimisation that keeps a battery alive longer.

Why Only 3, 5, 7 Appear as Three Primes in a Row

Among any three consecutive odd numbers, exactly one is divisible by 3. If that number is larger than 3, it is not prime. Therefore the only triple of primes of the form p, p + 2, p + 4 is (3, 5, 7). This is why the output of our program contains overlapping pairs only at the very start: (3, 5) and (5, 7) share the number 5, but no later pair shares a number with another pair.

Real-World Uses in Embedded C Programming

You will not usually search for twin primes inside a device, but the techniques are common. Calling a trusted predicate twice and combining the answers with && resembles checking two sensor limits at once. Counting how many times a function is called is a standard profiling trick when you have no profiler on a bare-metal target. And the idea of replacing a plain scan with a structured scan shows up in checksum tables, hash functions and schedulers. Each of these appears later in the free embedded C course.

Common Mistakes and Troubleshooting

MistakeSymptomFix
Stepping with p++Even candidates are tested, wasting timeUse p += 2 after starting at an odd number
Using || instead of &&Prints pairs where only one number is primeBoth must be prime, use &&
Loop limit p < 500Tests a pair whose second number is 501Use p + 2 < 500
Starting the loop at 2Tests the pair (2, 4)Start at 3
Expecting (2, 3) as a pairConfusion about the gapTwin primes differ by exactly 2

Best Practices, Performance and Security

Best practices

  • Keep the prime test in its own function so you can test it separately.
  • Express range limits so that their meaning is visible, such as p + 2 < 500.
  • Measure first with a counter, then optimise, and confirm that the answers stay identical.
  • Compare the new output with the old output before you trust an optimisation.

For performance, short-circuit evaluation and the 6k pattern both cut work. For security, remember that if the upper limit came from user input, you must check it before using it in a loop and before computing p + 2, because an unsigned value near its maximum can wrap around to a small number.

Summary and Key Takeaways

Remember

  • Twin primes are two primes that differ by exactly 2.
  • Use p += 2 and the condition p + 2 < limit for a correct loop.
  • The && operator skips the second test when the first fails.
  • Above (3, 5), twin primes have the form 6k – 1 and 6k + 1.
  • Counting calls is a simple way to prove that an optimisation helps.

Conclusion

You have written a twin primes program in C, verified that it finds 24 pairs below 500, and made a second version that does the same job with far fewer function calls. This is a strong example of how a small function, good boundaries and a little mathematics combine in embedded C programming. In the next lecture of this free C programming course we leave primes behind and convert decimal numbers to binary, a skill you will use constantly with registers.

Frequently Asked Questions

What are twin primes?

Twin primes are pairs of prime numbers that differ by exactly 2, for example 11 and 13 or 17 and 19.

How many twin prime pairs are there below 500?

There are 24 pairs. The smallest is (3, 5) and the largest is (461, 463).

How do you write a twin primes program in C?

Loop over odd numbers starting at 3, call a prime-test function on p and p + 2, and print the pair when both calls return 1.

Why is (2, 3) not a twin prime pair?

The numbers differ by 1, not 2. Two is the only even prime, so no other pair includes it.

Why does the 6k – 1 and 6k + 1 trick work?

Every prime above 3 leaves a remainder of 1 or 5 when divided by 6, so a twin pair must be of the form 6k – 1 and 6k + 1.

Why do the pairs (3, 5) and (5, 7) overlap?

Among three consecutive odd numbers one is a multiple of 3, so (3, 5, 7) is the only run of three primes with gaps of 2.

Is this tutorial available in a free embedded C course?

Yes. It is part of the free C tutorial series on EmbeddedPathashala, designed for students who want to learn C programming for embedded systems.

Keep Going With the Free Embedded C Course

Next we convert decimal numbers to binary, the skill you need to read and write hardware registers.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →