Finding the Number of Daffodils in C Language

The so-called narcissus number (NarcissisticNumber) refers to a 3-digit number, and the cube sum of its digits is equal to itself.
Ideas: (1) Decompose the digits of the number, and then find whether the sum of the cubes of each number is equal to the original number
(2) Combine 3 numbers to form a three-digit number, and find out whether the sum of the cubes of each number is equal to the number (note Hundreds digits start with 1)
For example 153 is "Daffodil number" because: 153 = 13 + 53 + 33.
Analysis: "Daffodil number" is a three-digit number, so the value range is 100~999.

C language implementation:

#include<stdio.h>
#include<math.h>

int main() {
    
    
    int unit, ten, hund;
    for (int i = 100; i < 1000; i++) {
    
    
        unit = i / 100;       //求百位数
        ten = (i / 10) % 10; //求十位数
        hund = i % 10;        //求个位数
        //if (i == hund * hund * hund + ten * ten * ten + unit * unit * unit)
        if (i == pow(hund, 3) + pow(ten, 3) + pow(unit, 3))
            printf("%d\n", i);
    }
}

C++ implementation:

#include <iostream>
#include <cmath>
using namespace std;

int main(){
    
    
    int n, unit, ten, hund; 
    for (n = 100; n < 1000; n++) {
    
    
        //将各个数位分离,得到个位、十位、百位。(注意百位数字从1开始)
        unit = n % 10;
        ten = (n / 10) % 10;
        hund = n / 100;
        // 判断各位数字的立方和是否等于它本身
        //if (n == hund * hund * hund + ten * ten * ten + unit * unit * unit)
        if (n == pow(hund, 3) + pow(ten, 3) + pow(unit, 3))
            cout << n << endl;
    }
    cout << endl;
    return 0;
}

Java implementation:

public class exercise_7 {
    
    
	public static void main(String[] args) {
    
    
	    int unit, ten, hund;
		for (int i = 100; i < 1000; i++) {
    
    
			unit = i / 100;       //求百位数
            ten = (i / 10) % 10; //求十位数
            hund = i % 10;        //求个位数
		   	if (i == hund * hund * hund + ten * ten * ten + unit * unit * unit) {
    
    
				System.out.println(i);
			}
		}
	}
}

Python implementation:

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

Guess you like

Origin blog.csdn.net/weixin_52088967/article/details/130117883