Blue Bridge Cup Daily One Question (5): sloppy calculations (python)

Topic:

Xiao Ming is impatient. When he was in elementary school, he often copied the questions his teacher had written on the blackboard wrong.
Once, the teacher asked the question: 36 x 495 =?
He copied it: 396 x 45 =?
But the result was dramatic, and his answer turned out to be correct! !
Because 36 * 495 = 396 * 45 = 17820
, there may be many coincidences like this, such as: 27 * 594 = 297 * 54
assuming that abcde represents 5 different numbers from 1 to 9 (note that they are different numbers, and Does not contain 0)
How many kinds of expressions can satisfy the form: ab * cde = adb * ce?
Please use the advantages of computers to find all the possibilities and answer the types and numbers of different calculations.
Formulas that satisfy the commutative law of multiplication are counted as different types, so the answer must be an even number.

Solution_1:

Direct violence solution
Arrange all a, b, c, d. e from 0 to 9
plus filter conditions:
(1) a, b, c, d, e all represent different numbers (not equal)
(2) satisfy ab * cde = adb * ce such a formula (according to the number of digits multiplied by 10 to the power of n)
, the result of satisfying the two conditions res + 1

Code_1:

res = 0

for a in range(1, 10):

    for b in range(1, 10):

        for c in range(1, 10):

            for d in range(1, 10):

                for e in range(1, 10):

                    if a != b and a != c and a != d and a != e and b != c and b != d and b != e and c != d and c != e \
                            and d != e and (a * 10 + b) * (c * 100 + d * 10 + e) == (a * 100 + d * 10 + b) * (
                            c * 10 + e):
                        res += 1

print(res)

Solution_2 (full permutation):
use the itertools module to simplify.
First use permutations to arrange all the elements of 5 digits to arrange all possible situations
. If ab * cde = adb * ce is satisfied (according to the number of digits multiplied by 10 to the power of n) )
Let res += 1

Code_2:

import itertools
res = 0

x = itertools.permutations([i for i in range(1, 10)], 5)

for j in x:
    if (j[0] * 10 + j[1]) * (j[2] * 100 + j[3] * 10 +j [4]) == (j[0] * 100 + j[3] * 10 + j[1]) * (10 * j[2] + j[4]):
        res += 1

print(res)

Answer:
142

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112488461