Blue Bridge Cup Daily One Question (7): Group prime numbers (python)

Topic:

A prime number is a number that cannot be divided equally. For example: 2 3 5 7 11 and so on.
9 = 3 * 3 means that it can be divided into 3 equal parts, so it is not a prime number.
Our country was founded in 1949. If you only give you the 4 digital cards 1 9 4 9 and you can place them in any order (but the cards can’t be placed backwards, we’re not thinking about it!), then how many 4 digits can you make? The prime number?
For example: 1949, 4919 all meet the requirements.

Solution:

Use full arrangement. After 1949,
after arranging the whole array by multiplying the number of digits by 10 to the power of n-1 to get the array after the whole arrangement,
perform prime judgment.
Set a number greater than 1.
If the original number is divided by the number and the remainder is 0, it means that the original number is not a prime number directly Judging the next number
Optimization:
As the two multipliers in the prime number judgment are viewed from small to large, after the
smaller prime number reaches the original number of the radical, the smaller number becomes larger and becomes larger, which
will lead to repeated judgments and decrease Efficiency
So only need to judge that the smaller number is less than the original number of the root sign.

It also needs to be judged when calculating again.
Finally, the length in the result array res is returned.

Code:

import itertools

x = list(itertools.permutations('1949'))
res = []

for i in x:
    number = int(i[0]) * 1000 + int(i[1]) * 100 + int(i[2]) * 10 + int(i[3])
    prime = True
    j = 2

    while j <= number ** 0.5:
        if number % j == 0:
            prime = False
            j += 1
            break
        else:
            j += 1
            pass

    if prime and number not in res:
        res.append(number)

print(res)

Answer:
6

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112585497
Recommended