Project Euler Solution 52: Permuted multiples

Here we have Problem 52: Permuted multiples which is about numbers where the multiples have the same digits in different orders.

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

First we need a function that determines whether a number has the same digits. We just convert to string and sort the characters.

def has_same_digits(first: int, second: int) -> bool:
    return sorted(str(first)) == sorted(str(second))

Then it is pretty easy to check the numbers. We know that n and 6 n has to have the same number of digits. This means that we only have to check numbers from say 100 to 166 when we want to check numbers with three digits. This means that there are lot less numbers to check.

This is the solution:

def solution() -> int:
    for digits in itertools.count(1):
        floor = 10 ** (digits - 1)
        ceiling = 10**digits // 6
        for number in range(floor, ceiling):
            for factor in range(2, 7):
                if not has_same_digits(number, number * factor):
                    break
            else:
                return number

This runs in 45 ms and I think that's fast enough.