Home > Article > Backend Development > How to output the number of all daffodils in python
Output method: First use the for statement to loop through all the numbers from 100 to 999, and assign it to the variable n; then decompose the variable n to obtain the ones digit k, tens digit j and hundreds digit i ; Finally, determine whether the cube sum of i, j and k numbers is equal to n. If so, just use the "print(n)" statement to output.
The operating environment of this tutorial: windows7 system, python3.7 version, DELL G3 computer
The so-called "daffodil number" refers to a three-dimensional A number of digits whose sum of cubes is equal to the number itself. For example: 153 is a "daffodil number" because 153=1 cubed + 5 cubed + 3 cubed.
python outputs the number of all daffodils
for n in range(100,1000): i = n // 100 j = n // 10 % 10 k = n % 10 if n == i ** 3 + j ** 3 + k ** 3: print (n)
Output:
153 370 371 407
Detailed explanation
Program analysis: using for Loop control 100-999 numbers, each number is decomposed into units, tens and hundreds.
First line:
for n in range(100,1000):
Because the narcissus number is a three-digit number, we loop through all the numbers from 100 to 999 and assign it to n
Second line:
i = n // 100
Divide 100 by n, and what you get is actually a three-digit hundred digit. Assign it to i
Third line:
j = n // 10 % 10
Divide 10 by n, and you will get a two-digit number consisting of hundreds and tens. Then divide this number by 10 to find the remainder. You will get our tens number, and assign it to j
The fourth line:
k = n % 10
Divide n by 10 and find the remainder. What you get is the single digit number of n. Assign it to k. At this time, the hundreds, tens and tens digits of the three-digit n are We have already obtained the single digits and assigned them to i, j, k respectively
The fifth line:
if n == i ** 3 + j ** 3 + k ** 3:
Judgment: If n is equal to the cube of its hundreds digits and ten digits If the cube is a single digit cube, then it is the narcissus number. At this time, print out the n that meets the conditions, otherwise it will enter the next loop
[Related recommendations: Python3 video tutorial 】
The above is the detailed content of How to output the number of all daffodils in python. For more information, please follow other related articles on the PHP Chinese website!