python classic 100 questions about the number of daffodils

Question: Print out all the "narcissus numbers". The so-called "narcissus number" refers to a three-digit number whose cube sum is equal to the number.

itself. For example: 153 is a "narcissus number" because 153=1 cubed + 5 cubed + 3 cubed.

Method 1: Brutal exhaustion method

Idea: Start with 100, enumerate each three-digit number in turn, and then find the cube sum of each digit of the number to determine whether the number is equal to the cube sum.

Advantages: The idea is simple, easy to understand and implement.

Disadvantages: The time complexity is high and all three-digit numbers need to be enumerated, so the efficiency is low.

The code is implemented as follows:

for num in range(100, 1000):
    temp = num
    sum = 0
    while temp:
        digit = temp % 10
        sum += digit ** 3
        temp //= 10
    if sum == num:
        print(num)

Method 2: Optimizing the exhaustive method

Idea: You can add some pruning operations to the exhaustive process. For example, you can only calculate the numbers whose sum is the specified value, which can reduce unnecessary calculations.

Advantages: Improved efficiency to a certain extent.

Disadvantage: Still need to enumerate all three digits.

The code is implemented as follows:

for i in range(1, 10):
    for j in range(0, 10):
        for k in range(0, 10):
            num = i * 100 + j * 10 + k
            if num == i ** 3 + j ** 3 + k ** 3:
                print(num)

Method 3: Mathematical formula method

Idea: According to the definition of narcissus number, we can get a three-digit formula for the sum of cubes of each digit, that is, num = i 3 + j 3 + k**3. According to this formula, you can quickly determine whether a number is a narcissus number.

Advantages: There is no need to enumerate all three-digit numbers, and the judgment is made directly based on the formula, which is more efficient.

Disadvantages: It is difficult to think and think of the formula.

The code is implemented as follows:

for num in range(100, 1000):
    i = num // 100
    j = num // 10 % 10
    k = num % 10
    if num == i**3 + j**3 + k**3:
        print(num)

To sum up, the mathematical formula method is the optimal solution, but it requires a certain understanding and mastery of mathematical formulas. Although the brute force exhaustive method is simple and easy to understand, it is less efficient. Optimizing the exhaustive method improves efficiency to a certain extent, but it still needs to enumerate all three-digit numbers.

Guess you like

Origin blog.csdn.net/yechuanhui/article/details/132870747