It is a three-digit number within 100-1000, for example: 153 = 1 1 1 + 5 5 5 + 3 3 3 This number is called the daffodil number.
C language implementation
The process is very simple, exhaustive, a number of cycles
// 水仙花数#include<stdio.h>#include<math.h>intmain(){
int b, s, g;for(int num =100; num <1000; num++){
b = num/100;
s = num/10%10;
g = num%10;// 使用计算幂的函数if(num ==(pow(b,3)+pow(s,3)+pow(g,3))){
printf("%5d\n", num);}}return0;}
python implementation
Note that the value of python needs to be converted with int(), because the value obtained by python division may be a floating-point type .
# 水仙花数for num inrange(100,1000):
b =int(num/100)
s =int(num/10)%10
g = num%10if num == b**3+ s**3+ g**3:print("水仙花数: ", num)
Generator implementation
As in the previous article, the Fibonacci sequence is realized, and the daffodil number is realized here.
In addition, the generator implementation is really convenient! We are not writing the iterator version. The generator automatically creates iter and next methods, which is really simple and simplified.
defhua():for num inrange(100,1000):
b =int(num/100)
s =int(num/10)%10
g = num%10if num == b**3+ s**3+ g**3:yield num
for i in hua():print(i)
结果:
153370371407