Project Euler

Problem 49: Prime permutations

The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.

There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.

What 12-digit number do you form by concatenating the three terms in this sequence?
Run this solution at repl.io here.

      
        from prime_list import prime_list

        # create a list of 4 digit primes
        primes1 = prime_list(10000)
        primes = [x for x in primes1 if x > 1000]


        for p in primes:
          subset = []
          digits_of_p = [int(d) for d in str(p)]
          for k in primes:
            digits_of_k = [int(d) for d in str(k)]
            # if k is a permutation of p
            if sorted(digits_of_k) == sorted(digits_of_p):
              #form a subset
              subset.append(k)
          #loop over indices of subset of prime permutations of p    
          for y in subset:
            diff = y - p
            for x in subset:
              # if difference exists again between two numbers in the subset
              # we have an arithmetic progression 
              # N.B take only positive (increasing) progressions
              if x - y == diff > 0:
                answer = (p,y,x)
                print(answer)
      
    

back to code menu