Python3 find the number of daffodils between 100-1000

What is the daffodil number?

The number of daffodils means that the sum of the cubes of each digit of this number is equal to this number. For example, 153 = 1^3 + 5^3 + 3^3, then 153 is a daffodil number.

Ideas:

You can find the digits on each digit of a certain number i separately, find the sum of the cubes of each digit, and judge whether sum and i are equal.

achieve

I thought of it when I was practicing

import math

for i in range(100, 1000):
    
    hundreds = int(i/100)
    tens_digit = int((i-100*hundreds)/10)
    single_digit = int(i-100*hundreds - 10*tens_digit)
    
    if i == (math.pow(hundreds, 3) + math.pow(tens_digit, 3) + math.pow(single_digit,3)):
        print(i,end = ' ')
    else:
        i += 1

The results are:

153 370 371 407 

In fact, there is a simpler way, I didn’t understand at the beginning o(╥﹏╥)o

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

The analysis is
mainly to explain the contents of the while loop:
Let’s take the number of daffodils as an example, assuming that i=153 and temp=1.

  1. temp= i = 153 The while loop is entered for the first time, and the main temp is not zero, the loop will continue to execute.
  2. temp%10 = 3, actually find the single digit, and assign the cube of the single digit to sum.
  3. temp // 10 = 15, floor division actually removes the single digits, leaving behind the hundreds and tens digits. At this time temp is not 0, continue the while loop
  4. temp%10 = 15 %10 = 5, in fact, the tens digit is calculated, and the cube of the tens digit is added to the sum.
  5. temp // 10 = 1, remove the tens digit, only the hundreds digit is left, at this time temp is still not 0, the loop continues
  6. temp%10 = 1%10 = 1, this is the number of hundreds digit, add the cube of 1 to sum.
  7. temp // 10 = 0 = temp, temp is finally 0, the while condition is judged to be false, exit the while loop, and execute the following if statement
  8. It is found that when i = 153, sum is exactly equal to i, so print i!

Reflection

  • The world of programming is really fun. Although the central idea is to find the value of each digit through a loop, the difference is really too big if you ask for the sum and skillfully.
  • You still have to think more, practice more, sum up more

Happy

  • It’s not long since I just started learning Python, but a long way to go
  • I hope to record the thinking process of interesting questions here
  • Novice thinking is not open enough, don’t spray if you don’t like it, and communicate with civilization.
  • Forgive me for having a tempered glass heart!

Guess you like

Origin blog.csdn.net/Haoyu_xie/article/details/105833175