Home Project Euler Teaching Projects Gallery

Problem 34: Digit factorials

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?


Algorthim:

Similar to last question, we need to find the limit to how far we should search for these numbers. Consider a 5 digit number. Then, the maximum digit factorials is 5 * 9! = 1814400. Let's look at 8 digits: 8 * 9! = 2903040, only has 7 digit. How about 7 digit? 7 * 9! = 2540160, which has 7 digit like we wanted! It's impossible for an 8 digit number to have its digit factorial to equal to its number. The maximum is 2903040 which only has 7 digits. So, we only have to check up to 2540160. Coding factorials and checking this is simple!

Code:

Result:

Answer: 40730
Runtime: 29.3 seconds