Just recently I discovered that there’s something called *sexy* prime numbers. I read about twin primes but hadn’t heard the other term before. The concept is pretty simple: take a prime number and check whether the next prime minus the first one results in a certain number, e.g. 2 for twin primes or 6 for sexy primes. This post presents a simple solution to calculate arbitrary combinations of prime number pairs, triplets, etc.

The Eclipse project with the code for this post can be downloaded as tar.gz or zip. You can browse the code online here.

## Preliminary

It’s likely that you already know how to calculate prime numbers but I’d like to show you a feasible approach anyway. The idea is based on the sieve of Eratosthenes: starting with the number 2, use it as a prime number if it isn’t divisible by any other prime number otherwise discard it. The advantage: easy to implement, the disadvantage: not that fast.

If we’d like to calculate the prime numbers starting with 2, up to 500 we could write the following code snippet:

for (int i = 2; i < 500; i++) { if (isDivisibleByPrime(i)) continue; primes.add(i); }

This implementation is simple yet fast enough for my purposes. Note that using Java’s primitive types it’s not possible to find prime numbers of arbitrary length; more work is required here if you want to do that.

## Arbitrary groups of primes

What I call a group here is a set of prime numbers differing by a particular number. One example would be triplets of prime number that differ by six, called the sexy prime triplets. You could think of many combinations, i.e. twins, triplets or quadruplets where the numbers differ by e.g. 2, 3 or 6.

The code that finds these sets of prime numbers is straight forward. It generates a list with prime numbers, searches for a given pattern – e.g. sexy prime triplets – and prints the results. By changing the parameters you can make up any combination you like but keep in mind that some will return an empty result.

Check out the file `PrimeGroups`

, specifically the top of the `main`

method. Try chaning the paramters `start`

, `end`

, `amount`

and `distance`

. Did you expect to get that many results for a certain pattern? It can be quite entertaining changing `amount`

and `distance`

, don’t you think?

## Conclusion

It’s easy and interesting to search prime numbers that match certain criteria. Have a look at the code and you’ll see that the implementation is pretty easy and doesn’t require extra coding skills if you don’t want to search for particularly large primes. Finally, it’s a nice exercise – even as a math novice – thinking about numbers and prime numbers in particular.