首页 > 试题广场 >

水仙花数

[编程题]水仙花数
  • 热度指数:11627 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的:“水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153=1^3+5^3+3^3。 现在要求输出所有在m和n范围内的水仙花数。


输入描述:
输入数据有多组,每组占一行,包括两个整数m和n(100<=m<=n<=999)。


输出描述:
对于每个测试实例,要求输出所有在给定范围内的水仙花数,就是说,输出的水仙花数必须大于等于m,并且小于等于n,如果有多个,则要求从小到大排列在一行内输出,之间用一个空格隔开;如果给定的范围内不存在水仙花数,则输出no;每个测试实例的输出占一行。
示例1

输入

100 120 
300 380

输出

no
370 371
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n, m;
        while (true) {
            System.out.println("请输入两个整数m,n(其中m,n均在100到999之间):");
            n = scanner.nextInt();
            m = scanner.nextInt();
            if (n<100 || n > 999 || m<100 || m > 999) {
                System.out.println("你输入的数不符合要求,请重新输入!");
                continue;
            }
            break;
        }
        List<Integer> shuixianhuaNum = printShuixianhuaNum(n, m);
        if (shuixianhuaNum.size() == 0) {
            System.out.println(m + "和" + n + "之间没有水仙花数!");
        } else {
            System.out.println(m + "和" +n+"范围内的水仙花数为:" + shuixianhuaNum);
        }
    }

    private static List<Integer> printShuixianhuaNum(int n, int m) {
        n = n <= m ? n : m;
        m = n >= m ? n : m;
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = n; i <= m; i++) {
            int ge = i % 10;
            int shi = i / 10 % 10;
            int bai = i / 100 % 10;
            if (ge * ge * ge + shi * shi * shi + bai * bai * bai == i) {
                list.add(i);
            }
        }
        return list;
    }
结果:
请输入两个整数m,n(其中m,n均在100到999之间):
100
999
999和100范围内的水仙花数为:[153, 370, 371, 407]
发表于 2019-09-08 14:58:28 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m , n, a, b, c;
        boolean flag;
        // sc.hasNext() : 当控制台输入不是"-"时,就将其压入栈中,当输入为"-",栈不为空则弹出。
        while (sc.hasNext()){
            m = sc.nextInt();
            n = sc.nextInt();
            flag = false;
            for (int i = m ; i <= n; i++){
                a = i / 100;
                b = i % 100 /10;
                c = i % 10;
                if (i == a*a*a + b*b*b + c*c*c) {
                    flag = true;
                    System.out.print(i + " ");
                }
            }
            if (!flag) {
                System.out.print("no");
            }
            System.out.println();
        }
    }
}

发表于 2021-02-26 11:30:17 回复(0)
#include <bits/stdc++.h>
using namespace std;

bool F(int x){
    int a=x/100, b=(x/10)%10, c=x%10;
    return a*a*a + b*b*b + c*c*c == x;
}

int main(){
    int m, n;
    int a[1000] = {0};
    for(int i=100;i<=999;i++)
        a[i] = a[i-1] + F(i);
    while(cin>>m>>n){
        if(a[n]==a[m-1])
            puts("no");
        else{
            for(int i=m;i<=n;i++)
                if(a[i]!=a[i-1])
                    printf("%d ", i);
            printf("\n");
        }
    }
    return 0;
}

发表于 2020-12-18 23:03:58 回复(0)
#暴力求解
while True:
    try:
        m, n = map(int, input().split())
        lis = []
        for i in range(m, n + 1):
            a, b, c = i // 100, i // 10 % 10, i % 10
            if i == pow(a, 3) + pow(b, 3) + pow(c, 3):
                lis.append(str(i))
        if len(lis) == 0:
            print('no')
        else:
            print(' '.join(lis))
    except:
        break

发表于 2020-04-16 20:42:26 回复(0)
知识点:
1.cmath.h头文件使用,幂次运算:pow(x,y),求x的y次幂值。

解题思路:
1.读取上下区间数,循环搜索区间内的水仙花数

C++代码实现:
#include<iostream>
#include<cmath>
using namespace std;
bool Daffodil_number(int x);
int main()
{
    int m,n;
    while(cin>>m>>n){
        bool flag=false;
        for(int i=m;i<=n;i++){
            if(Daffodil_number(i)){
                flag=true;
                cout<<i<<" ";
            }
        }
        if(flag){
            cout<<endl;
        }
        else{
            cout<<"no"<<endl;
        }
    }
    return 0;
}
bool Daffodil_number(int x)
{
    return (pow((x%10),3)+pow((x/10%10),3)+pow((x/100),3)==x);
}
发表于 2019-09-15 21:47:55 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int m,n;
    while(cin>>m>>n)
    {
        int res=0;
        for(int i=m;i<=n;i++)
        {
            int k=i,sum=0;
            while(k)
            {
                sum+=pow(k%10,3);
                k/=10;
            }
            if(sum==i)
            {
                
                if(res>0)
                    cout<<" ";
                cout<<i;
                res++;
            }
        }
        if(res==0)
            cout<<"no";
        cout<<endl;
    }
    return 0;
}

发表于 2019-06-26 19:30:13 回复(0)
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
bool Judge(int x){
    int a = x / 100,b=x/10%10,c=x%10%10;
    if ((pow(a, 3) + pow(b, 3) + pow(c, 3)) == x)
        return true;
    else
        return false;
}
int main(){
    int m,n,number=0,rec=0;
    vector<int> v1, v2;
    while (cin >> m >> n){
        v1.push_back(m);
        v2.push_back(n);
        number++;
    }
    while (rec<number){
        int s = 0;
        if (v1[rec] > v2[rec]){
            cout << "no" << endl;
            continue;
        }
        for (int i = v1[rec]; i <= v2[rec]; i++){
            if (Judge(i)){
                s++;
                cout << i << " ";
                continue;
            }
        }
        if (s == 0)
            cout << "no";
        cout << endl;
        rec++;
    }
    system("pause");
    return 0;
}

发表于 2019-04-21 11:21:14 回复(0)
#include<iostream>
using namespace std;
int main()
{
    int m,n;
    while(cin>>m>>n)
    {
        m<=153&&n>=407 ? cout<<"153 370 371 407":(m<=153&&n>=371 ? cout<<"153 370 371":(m<=370&&n>=407 ? cout<<"370 371 407":(m<=153&&n>=370 ? cout<<"153 370":(m<=370&&n>=371 ? cout<<"370 371":(m<=371&&n>=407 ? cout<<"371 407":(m<=153&&n>=153 ? cout<<"153":(m<=370&&n>=370 ? cout<<"370":(m<=371&&n>=371 ? cout<<"371":(m<=407&&n>=407 ? cout<<"407":cout<<"no")))))))));
        cout<<endl;
    }
}

发表于 2019-01-28 16:10:37 回复(0)
def is_narcissistic_number(num):
    # 判断一个数是否为水仙花数
    sum_of_cubes = sum(int(x) ** 3 for x in str(num))  # 计算各位数字的立方和
    return sum_of_cubes == num  # 返回是否为水仙花数的布尔值

while True:
    try:
        m, n = map(int, input().split())  # 输入范围m和n
        narcissistic_numbers = [str(num) for num in range(m, n+1) if is_narcissistic_number(num)]  # 找出范围内的水仙花数
        if narcissistic_numbers:
            print(" ".join(narcissistic_numbers))  # 输出水仙花数,用空格分隔
        else:
            print("no")  # 若范围内不存在水仙花数,输出"no"
    except:
        break  # 异常处理,结束循环
#chatgpt写的
编辑于 2024-03-15 18:13:06 回复(0)
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    // Write your code here
    while(line = await readline()){
        let arr=line.split(' ').map(Number).sort((a,b)=>a-b)
   let array=[]
   for(let i=arr[0];i<=arr[1];i++){
     if(is(i)){
        array.push(i)
     }
   }
   if(array.length===0){
    console.log('no')
   }else if(array.length===1){
    console.log(array.join(''))
   }else{
    console.log(array.join(' '))
   }
    }
}()
function is(n){
    const b=Math.floor(n/100)
    const s=Math.floor(n/10)%10
    const g=n%10
    return n===Math.pow(b,3)+Math.pow(s,3)+Math.pow(g,3)
}

编辑于 2024-02-05 16:32:45 回复(0)
package main

import (
    "fmt"
)

func main() {
    var m,n int
    for{
        _,err:=fmt.Scan(&m,&n)
        if err!=nil{
            break
        }
        ans:=[]int{}
        for i:=m;i<=n;i++{
            if check(i){
                ans=append(ans,i)
            }
        }
        if len(ans)==0{
            fmt.Println("no")
        }else{
            for _,x:=range ans{
                fmt.Printf("%v ",x)
            }
            fmt.Println()
        }
    }
}

func check(x int)bool{
    ori:=x
    sum:=0
    for x>0{
        y:=x%10
        sum+=y*y*y
        x/=10
    }
    return sum==ori
}

发表于 2023-03-04 19:43:57 回复(0)
while(line = readline()){
    lines = line.split(' ')
    var result =[]
    for(let i =Number(lines[0]);i<=Number(lines[1]);i++){
        let x,y,z;
        var str = String(i);
        x = Number(str.charAt(0));
        y = Number(str.charAt(1));
        z = Number(str.charAt(2));
        if(Math.pow(x,3)+Math.pow(y,3)+Math.pow(z,3) == i){
            result.push(i)
        }
    }
    if(result.length>0){
        console.log(result.join(' '))
    }else{
        console.log('no')
    }
    
}

发表于 2022-08-31 15:51:23 回复(0)
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    vector<int> all_nums;
    for (int i = 1; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            for (int k = 0; k < 10; k++) {
                int n = k + j * 10 + i * 100;
                if (n == k * k * k + j * j * j + i * i * i) {
                    all_nums.push_back(n);
                }
            }
        }
    }
    
    int m, n;
    while (cin >> m >> n) {
        string result = "";
        for (int i = 0; i < all_nums.size(); i++) {
            if (all_nums[i] >= m) {
                int j = i;
                while (j < all_nums.size() && 
                       all_nums[j] >= m && all_nums[j] <= n) {
                    result += to_string(all_nums[j]);
                    result += " ";
                    j++;
                }
                break;
            }
        }
        
        if (result == "") cout << "no" << endl;
        else cout << result.substr(0, result.size()-1) << endl;
    }
}

发表于 2022-08-30 23:55:41 回复(0)
package main

import(
    "fmt"
    "io"
)

func main(){
    m,n := 0,0
    _,err:=fmt.Scan(&m,&n)
    for err!=io.EOF{
        ans:=[]int{}
        flag:=false
        for m<=n{
            
            hund:=m/100
            ten:=(m-hund*100)/10
            one:=m-hund*100-ten*10
            arr:=[3]int{hund,ten,one}
            
            if m==arr[0]*arr[0]*arr[0]+arr[1]*arr[1]*arr[1]+arr[2]*arr[2]*arr[2]{
                ans=append(ans,m)
                flag=true
            }
            m++
        }
        if !flag{
            fmt.Println("no")
        }else{
            for _,v:=range ans{
                fmt.Print(v)
                fmt.Print(" ")
            }
            fmt.Println()
        }
   
        _,err=fmt.Scan(&m,&n)
    }
}

发表于 2022-04-10 07:58:34 回复(0)
while True: try:
        m,n = map(eval , input().split())
        list0=[] for i in range(m, n + 1): if (i // 100) ** 3 + (i // 10 % 10) ** 3 + (i % 10) ** 3 == i:
                list0.append(i) else: continue  if list0 == []: print('no') else: for j in list0: print(j,end=' ') print() except: break 
发表于 2022-02-18 15:12:28 回复(0)
封装一下
import java.util.Scanner;
public class Main {
    public static void main (String[] arg0) {
        Scanner sca = new Scanner(System.in);
        while (sca.hasNext()) {//接口
            test(sca.nextInt(), sca.nextInt());
        }
    }
    //循环体
    public static void test (int m, int n) {
        boolean temp = false;
        for (int i = m; i <= n; i++) {
            if (panduan(i)) {
                System.out.print(i + " ");
                temp = true;
            }
        }
        if (!temp) {
            System.out.print("no");
        }
        System.out.println();
    }
    //判断方法
    public static boolean panduan (int num) {
        int a = 0;
        int t = num;
        int r = 0;
        while (t != 0) {
            a = t % 10;
            r += (int)Math.pow(a, 3);
            t /= 10;
        }
        if (r == num) return true;
        return false;
    }
}


发表于 2022-01-26 23:47:52 回复(0)
#include <stdio.h>
#include <stdlib.h>

int check(const int num) {
  int x = num, d, s = 0;
  while (x) {
    d = x % 10;
    s += d * d * d;
    x /= 10;
  }
  return s == num;
}

int main(const int argc, const char** argv) {
  int m, n;
  while (scanf("%d %d", &m, &n) != EOF) {
    int num, count = 0;
    for (num = m; num <= n; ++num) {
      if (check(num)) {
        fprintf(stdout, "%d ", num);
        ++count;
      }
    }
    if (count == 0) fputs("no", stdout);
    fputc(10, stdout);
  }
  
  return 0;
}

发表于 2021-07-15 18:55:32 回复(0)
TreeSet预处理:
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        TreeSet<Integer> set = new TreeSet<Integer>();
        for(int i = 100; i < 1000; i++){
            if(check(i)){
                set.add(i);
            }
        }
        while((line = br.readLine()) != null){
            String[] s = line.split(" ");
            int m = Integer.parseInt(s[0]);
            int n = Integer.parseInt(s[1]);
            boolean flag = false;
            for(int i : set){
                if(i >= m && i <= n){
                    flag = true;
                    System.out.print(i + " ");
                }
            }
            if(flag)System.out.println();
            else {
                System.out.println("no");
            }
        }
    }
    public static boolean check(int num){
        int num1 = num % 10;
        int num2 = num /10 % 10;
        int num3 = num /100;
        return cube(num1) + cube(num2) + cube(num3) == num;
    }
    public static int cube(int n){
        return n * n * n;
    }


发表于 2021-05-20 16:45:28 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int m = scanner.nextInt();
            int n = scanner.nextInt();
            boolean flag = false;
            for (int i = m; i <= n; i++) {
                int[] digits = new int[3];
                digits[0] = i % 10;
                int temp = i / 10;
                digits[1] = temp % 10;
                temp = temp / 10;
                digits[2] = temp % 10;
                if (i == powerSum(digits)) {
                    flag = true;
                    System.out.print(i + " ");
                }
            }
            if(flag == false){
                System.out.println("no");
            }else{
                System.out.println();
            }
        }
    }

    private static int powerSum(int[] digits) {
        return digits[0] * digits[0] * digits[0] +
            digits[1] * digits[1] * digits[1] +
            digits[2] * digits[2] * digits[2];
    }


}

发表于 2021-04-21 13:28:10 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            int m = scan.nextInt();
            int n = scan.nextInt();
            boolean hasFlower = false;
            for(int i = m; i <= n; i++){
                if(isFlower(i)){
                    System.out.print(i + " ");
                    hasFlower = true;
                }
            }
            if(!hasFlower)
                System.out.println("no");
            else
                System.out.println();
        }
    }
    private static boolean isFlower(int x){
        int temp = 0, record_x = x;
        while(x != 0){
            if(temp > record_x)
                return false;
            temp += (x % 10)*(x % 10)*(x % 10);
            x /= 10;
        }
        if(record_x == temp)
            return true;
        else
            return false;
    }
}
发表于 2021-04-09 19:45:40 回复(0)