【蓝桥杯】46195.水仙花数

水仙花数

问题描述

打印所有100至999之间的水仙花数。所谓水仙花数是指满足其各位数字立方和为该数字本身的整数,例如 153=13+53+33

样例输入

样例输出

matlab 复制代码
153
370
371
407

解题思路

  1. 遍历100到999之间的所有整数。
  2. 对每个整数,计算其各位数字的立方和。
  3. 如果立方和等于该数字,则打印该数字。

代码展示

Python 实现

python 复制代码
# 遍历100到999之间的所有数字
for num in range(100, 1000):
    # 将数字拆解成个位、十位、百位数字
    a = num // 100            # 百位
    b = (num // 10) % 10      # 十位
    c = num % 10              # 个位
    
    # 计算各位数字的立方和
    if a**3 + b**3 + c**3 == num:
        print(num)

JAVA 实现

java 复制代码
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改

public class Main {
    public static void main(String[] args) {
        for (int num = 100; num < 1000; num++) {
            // 计算百位数字
            int a = num / 100;
            // 计算十位数字
            int b = (num / 10) % 10;
            // 计算个位数字
            int c = num % 10;

            // 计算各位数字的立方和并判断是否与原数字相等
            if (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3) == num) {
                System.out.println(num);
            }
        }
    }
}

C++ 实现

cpp 复制代码
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    for (int num = 100; num < 1000; num++) {
        // 计算百位数字
        int a = num / 100;
        // 计算十位数字
        int b = (num / 10) % 10;
        // 计算个位数字
        int c = num % 10;
        
        // 计算各位数字的立方和并判断是否与原数字相等
        if (pow(a, 3) + pow(b, 3) + pow(c, 3) == num) {
            cout << num << endl;
        }
    }
    
    return 0;
}

C 实现

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
    int num;
    for (num = 100; num < 1000; num++) {
        // 计算百位数字
        int a = num / 100;
        // 计算十位数字
        int b = (num / 10) % 10;
        // 计算个位数字
        int c = num % 10;
        
        // 计算各位数字的立方和并判断是否与原数字相等
        if (pow(a, 3) + pow(b, 3) + pow(c, 3) == num) {
            printf("%d\n", num);
        }
    }
    
    return 0;
}

运行结果

matlab 复制代码
>>> 
153
370
371
407
>>> 
相关推荐
用户8356290780511 天前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon1 天前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程1 天前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风2 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python